Will Ashley Will Ashley - 1 year ago 67
Ruby Question

Ruby using regex in select block

I've been having a lot of trouble sifting out regex matches. I could use scan, but since it only operates over a string, and I dont want to use a join on the array in question, it is much more tedious. I want to be able to do something like this:

array = ["a1d", "6dh","th3"].select{|x| x =~ /\d/}
# => ["1", "6", "3"}

However this never seems to work. Is there a work around or do I just need to use scan?

Answer Source

Try: Array#map

> array = ["a1d", "6dh","th3"].map {|x| x[/\d+/]}
#=> ["1", "6", "3"] 

Note: select

Returns a new array containing all elements of ary for which the given block returns a true value.

In your case each element contains digit and it returns true, so you are getting original element via select. while map will perform action on each element and return new array with performed action on each element.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download