hoow to match a complete word in ruby?
def find_word(text, word)
regex = /\b#{word}\b/
matches = text.scan(regex)
matches.empty? ? "Word '#{word}' not found." : "Word '#{word}' found."
end
text = "Ruby is a programming language. Ruby is fun to learn and use!"
word_to_find = "Ruby"
puts find_word(text, word_to_find)
Explanation:
find_word
is a function defined to search for a specific word within a given text.text
variable holds the input text where the word will be searched.word_to_find
variable contains the word you want to find within the text.\b
in theregex
variable signifies a word boundary in regular expressions.#{word}
inserts the word to be found within the regular expression pattern.text.scan(regex)
looks for all matches of the given word in the text.- If matches are found, it returns "Word 'Ruby' found."; otherwise, it returns "Word 'Ruby' not found."