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.
Fddbb3cd16868f4741c2e86ef015a639?d=identicon&s=25 Sergio T. Ruiz (sergio101)
on 2008-11-20 20: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!
F50f5d582d76f98686da34917531fe56?d=identicon&s=25 Peter Szinek (Guest)
on 2008-11-20 20:05
(Received via mailing list)
On 2008.11.20., at 19:57, Sergio Ruiz 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
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-11-20 21:19
Sergio Ruiz 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"
Fddbb3cd16868f4741c2e86ef015a639?d=identicon&s=25 Sergio T. Ruiz (sergio101)
on 2008-11-20 21:41
everyone rules!

thanks, guys!
44a18ce7b037350c02e9ca0e8e9a856c?d=identicon&s=25 Matthew Campbell (codethis)
on 2013-11-20 17: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"]
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2013-11-20 21:52
There's also this option:
a.any? { |val| /^coo/ =~ val }
This topic is locked and can not be replied to.