Array.include? with a regex?


#1

i am wondering if this is possible… i can’t seem to figure it out…

i am trying to see if a value is inside an array using regex…

something like:

a = [“pie”,“cookies”,“soda”,“icecream”]

i want to see if something starts with “coo” i should get one…

it doesn’t look like i am doing it correctly…

irb(main):010:0> a.include?(/^coo/)
=> false

ideas?

thanks!


#2

On 2008.11.20., at 19:57, Sergio R. wrote:

it doesn’t look like i am doing it correctly…

irb(main):010:0> a.include?(/^coo/)
=> false

ideas?

Enumerable#grep:

a = [“pie”,“cookies”,“soda”,“icecream”]
a.grep /^coo/

Cheers,
Peter


http://www.rubyrailways.com
http://scrubyt.org


#3

Sergio R. wrote:

i am wondering if this is possible… i can’t seem to figure it out…

i am trying to see if a value is inside an array using regex…

something like:

a = [“pie”,“cookies”,“soda”,“icecream”]

i want to see if something starts with “coo” i should get one…

irb(main):001:0> a = [“pie”,“cookies”,“soda”,“icecream”]
=> [“pie”, “cookies”, “soda”, “icecream”]
irb(main):002:0> a.find { |e| /^coo/ =~ e }
=> “cookies”


#4

Sergio T. Ruiz wrote in post #751409:

everyone rules!

thanks, guys!

When checking whether the array “includes” the regex expression, you’re
in fact asking whether the array’s elements MATCH that expression.

Bad:
a = [“pie”,“cookies”,“soda”,“icecream”]
a.include?(/^coo/)
=> false

Good:
a = [“pie”,“cookies”,“soda”,“icecream”]
a.select{|food| food.match(/^coo/)}
=> [“cookies”]


#5

There’s also this option:
a.any? { |val| /^coo/ =~ val }


#6

everyone rules!

thanks, guys!