Kit Ho Kit Ho - 7 months ago 13
Ruby Question

Match a pattern in an array

There is an array with 2 elements

test = ["i am a boy", "i am a girl"]


I want to test if a string is found inside the array elements, say:

test.include("boy") ==> true
test.include("frog") ==> false


Can i do it like that?

Answer

Using Regex.

test = ["i am a boy" , "i am a girl"]

test.find { |e| /boy/ =~ e }   #=> "i am a boy"
test.find { |e| /frog/ =~ e }  #=> nil