I have this code:
result=
["MA-1", "NY-2", "CT-2", "NJ-1", "NJ-2", "NJ-3"].select do |element|
element.match '2'
end
Is there a way to use the &
shortcut without using a separate proc?
I tried:
["MA-1", "NY-2", "CT-2", "NJ-1", "NJ-2", "NJ-3"].select(&:match('2'))
which raises a syntax error.
It seems like you can use grep
:
["MA-1", "NY-2", "CT-2", "NJ-1", "NJ-2", "NJ-3"].grep(/2/)
#=> ["NY-2", "CT-2", "NJ-2"]
Or with the custom proc:
my_proc = ->(e) { e.match('2') }
["MA-1", "NY-2", "CT-2", "NJ-1", "NJ-2", "NJ-3"].select(&my_proc)
#=> ["NY-2", "CT-2", "NJ-2"]
Or (credits to @engineersmnky):
select(&/2/.method(:match))