|
|
|
|
|
by Toutouxc
1954 days ago
|
|
No, passing a symbol and sending is a different mechanism. The send method is basically the same thing as calling a method by name, as in "obj.foo" == "obj.send(:foo)". If you only pass a symbol into your "caller" method, the symbol goes through the normal lookup: does the receiving object respond to this? If yes, then that implementation (at that exact moment) is called, if not, you get a method_missing. You're right that that's
not how you do first-class functions in ruby.
Your example in ruby would be: def get_and_call(fn, x)
fn.call(x)
end
def upcasinator_method(str)
str.upcase
end
upcasinator_lambda = lambda {|str| str.upcase}
get_and_call(upcasinator_lambda, 'foobar')
=> "FOOBAR"
get_and_call(method(:upcasinator_method), 'foobar')
=> "FOOBAR"
As you can see there are two ways to do that -- either you create a Proc (a lambda if you care about arity), which is the first class function in Ruby, and you call that, or you define a method (but that's a method, an OOP concept, a procedure that implicitly operates on an object), you get a hold of it using the "method" method and then you call it. |
|