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 JavaScript, we often call these functions. In Ruby, we call them methods because everything is an object and all functions are called on objects. All methods are functions, but the reverse isn't necessarily true. "Hello world!" is an instance of the class String .
Ruby is a pure object-oriented language, which means that in the Ruby language, everything is an object. These objects, regardless of whether they are strings, numbers, classes, modules, etc., operate in a system called The Object Model. Ruby offers a method called the object_id , which is available to all objects.
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
You simply use the method
method. This will return the Method
instance that matches with that method. Some examples:
>> def f
>> "foo"
>> end
=> nil
>> f
=> "foo"
>> method(:f)
=> #<Method: Object#f>
>> method(:f).methods
=> [:==, :eql?, :hash, :clone, :call, :[], ...]
>> class SomeClass
>> def f
>> "bar"
>> end
>> end
=> nil
>> obj = SomeClass.new
=> #<SomeClass:0x00000001ef3b30>
>> obj.method(:f)
=> #<Method: SomeClass#f>
>> obj.method(:f).methods
=> [:==, :eql?, :hash, :clone, :call, :[], ...]
Hope this helps.
The method method
will give you a Method
object
f = obj.method :f
puts f.call # or f[]
this f
is bound to obj. You can also get an unbound method:
unbound_plus = Fixnum.instance_method('+')
plus_2 = unbound_plus.bind(2)
(There is also a unbind method)
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