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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With