Hiii,
Hi!
i am new to this ruby-talk list, so i hope my question is not annoying
(especially for my not so goood english).
Not at all. As you might have seen from other messages today, we're
hungry for some actual Ruby discussion.
My question is simple. Is there a way to store a method in a variable? I
know that every method can be called with the keyword and send, but is
there a way to make it direct callable?
Yes. Functions and methods (they're both the same construct really) can
be held in objects of the Method class, which are obtained by calling
`obj.method(:method_name)`. Omit the receiver for functions/global
methods like `puts`.
As example:
def addition(a, b)
a + b
end
x = addition
x(2, 3) # => 5
Is there a method like partial or anything like this in ruby?
See this snippet:
def addition(a, b)
a + b
end
x = method(:addition)
puts x.call(2, 3)
puts x[2, 3] # syntax sugar; however, note instead of ()
class Foo
attr_accessor :a
def initialize(a)
self.a = a
end
def addition(b)
self.a + b
end
end
# For methods inside of classes:
f = Foo.new(2)
x = f.method(:addition)
puts x.call(3)
puts x[3]
···
On Mon, Jun 30, 2014, Addis Aden wrote:
best wishes,
Adrian
___
@addisaden