ruby match word in string

Matching a Word in a String in Ruby

To match a word in a string in Ruby, you can use regular expressions. Regular expressions allow you to search for patterns in strings and perform various operations, including matching words.

Here's an example of how you can match a word in a string using Ruby:

string = "The quick brown fox jumps over the lazy dog"
word = "fox"

if string.match?(/\b#{word}\b/)
  puts "The word '#{word}' is present in the string."
else
  puts "The word '#{word}' is not present in the string."
end

Explanation of the code: 1. We define a string variable string that contains the sentence we want to search. 2. We define a word variable word that represents the word we want to match. 3. We use the match? method with a regular expression pattern /\b#{word}\b/ to check if the word is present in the string. - \b is a word boundary anchor that matches the position between a word character and a non-word character. - #{word} is a placeholder that inserts the value of the word variable into the regular expression pattern. 4. If the word is present in the string, we print a message indicating its presence. Otherwise, we print a message indicating its absence.

This code will output:

The word 'fox' is present in the string.

Note: The regular expression pattern \b#{word}\b ensures that the word is matched as a whole word and not as part of another word. The \b anchors ensure that the word is surrounded by word boundaries.

Please let me know if you need any further assistance!