In Ruby, everything is supposed to be an object. But I have a big problem to get to the function object defined the usual way, like
def f
"foo"
end
Unlike in Python, f is the function result, not the function itself. Therefore, f()
, f
, ObjectSpace.f
are all "foo"
. Also f.methods
returns just string method list.
How do I access the function object itself?
In Ruby, what you are asking for does not make sense. (It makes sense in languages like Python, JavaScript, Java, and C#.)
In Ruby, you can tell a class what messages it should respond to and in what ways it should respond to those messages. The most common way to tell a class that is to define a method in the class. But again, that simply means: when someone sends the message
f
to this instance, here's the behavior that the instance should respond with. There is no function object.You can do things like get a symbol (
method_name = :foo
) and get a closure (method = proc { obj.foo }
).The method
method
will give you aMethod
objectthis
f
is bound to obj. You can also get an unbound method:(There is also a unbind method)
You can obtain an object that will correspond to that function at runtime, but as far as I know there's no equivalent to what Python allows you to do right there in the function/class definition.
Hopefully someone will prove me wrong, but I've never been able to pull it off.
well I have found the answer myself
thank you all for the inspiration :)
You simply use the
method
method. This will return theMethod
instance that matches with that method. Some examples:Hope this helps.
You should create a
Proc
object if you want a function objectyou call the function using either
or
you may even use this function object in a
map
operation