Example of a simple combination of different methods/operators in ruby


sentence = %w(This is a good example)
sentence.keep_if { |word| word =~ /[o]/ }
p sentence

In the above code, there are two methods used. ‘keep_if’ deletes every element of self for which the block returns false. The operator ‘=~’ works in matching strings against regular expressions. Such as in the code above, its working to match /[o]/ (letter ‘o’) present in either of the words of the sentence. The code returns [“good”] in an array form as the symbol ‘%w’ is a shortcut notation to write an array. If the =~ does not match anything in the string and regular expression, it returns the value as ‘nil’.