Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand for {|x| foo x}?

Tags:

ruby

I have defined a method that I want to apply to a list:

class Foobar
  def foo(x)
    x+1
  end

  def bar(list)
    list.map {|x| foo x}
  end
end

I was expecting to be able to do something like list.map(foo) as it seems rather redundant to create a lambda function that just applies its arguments to a function.

like image 477
Nowhere man Avatar asked Oct 01 '19 14:10

Nowhere man


2 Answers

You can reference the method to pass as a proc with method:

list.map(&method(:foo))

Maybe not the shortcut you're looking for, as it's limited to work with methods that expect only one argument and reduces readability.

like image 197
Sebastian Palma Avatar answered Sep 21 '22 16:09

Sebastian Palma


Adding a bit more context to the answer supplied by Sebastian Palma.

method(:foo)

Returns the method foo of the current instance (self). You can also use this in combination with other instances:

(1..10).map(&5.method(:+))
#=> [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Here 5.method(:+) returns the + method for the instance 5.

like image 38
3limin4t0r Avatar answered Sep 18 '22 16:09

3limin4t0r