The following command works in Ruby 1.9.3p194
> %w(a b c).grep(/a/) { |v| v.upcase }
=> ["A"]
But if any element in the array has a slash in it, a SyntaxError is thrown:
> %w(a/ b c).grep(/a/) { |v| v.upcase }
SyntaxError: (irb):41: syntax error, unexpected tMATCH
%Q/a// =~ /a/
I’m assuming I’m using grep incorrectly but the error I’m getting is really confusing. Why does it throw this error, and what is the proper way to find an element in an array based on a regex?
Update:
Select gives me what I want, but I’m still curious what grep is for…
> %w(a/ b c).select {|v| v =~ /a/ }
=> ["a/"]
Turns out it’s neither Ruby nor Rails, but a gem called awesome_print which is monkey patching Ruby’s grep method. I was using an old version which must have had some bugs. Upgrading to the latest version 1.0.2 fixes the issue.