Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ruby function object itself

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?

like image 514
mykhal Avatar asked Dec 19 '09 16:12

mykhal


People also ask

Is a function an object in Ruby?

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 .

Why everything is object in Ruby?

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.

What is self method in Ruby?

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.


2 Answers

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.

like image 160
sarahhodne Avatar answered Oct 31 '22 21:10

sarahhodne


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)

like image 3
Justin Love Avatar answered Oct 31 '22 21:10

Justin Love