Forum: Ruby Array.include? with a regex?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Sergio T. R. (Guest)
on 2008-11-20 21:01
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!
Peter S. (Guest)
on 2008-11-20 21:05
(Received via mailing list)
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
Brian C. (Guest)
on 2008-11-20 22:19
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"
Sergio T. R. (Guest)
on 2008-11-20 22:41
everyone rules!

thanks, guys!
Matthew C. (Guest)
on 2013-11-20 18:52
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"]
Joel P. (Guest)
on 2013-11-20 22:52
There's also this option:
a.any? { |val| /^coo/ =~ val }
This topic is locked and can not be replied to.