Michael Durrant
Michael Durrant

Reputation: 96484

Can I use '&' shorthand for selecting matches?

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.

Upvotes: 0

Views: 238

Answers (2)

Ilya
Ilya

Reputation: 13487

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))

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

[can I do this] without using a separate proc

No. Primarily because neither & nor symbols are methods or anything that can accept parameters. You must use the full form.

Upvotes: 2

Related Questions