Kit Ho Kit Ho - 2 years ago 92
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download