views:

77

answers:

1

In Ruby, how do you refer to a function without invoking it, because foo is the same as foo() so it is already invoked.

for example, puts.class is the same as puts().class

+6  A: 

You use method, like so:

o = Object.new
def o.do_it
  puts "I did it!"
end

m = o.method(:do_it)
m.call    # prints out "I did it!"
John Hyland
I just tried defining a global function called foo, and then both `method(:foo)` and method(:puts) both work... so can method() be used whenever the method is inherited from ancestor?
動靜能量
@Jian Lin: `method` itself is just a method that returns the method that would be called if you sent the receiver the message named by the argument. So `self.method(:foo)` returns the method that would be performed if you did `self.foo`, and `"hello".method(:downcase)` is the method that would be called if you wrote `"hello".downcase`. As always, methods can be inherited, and those count for purposes of this method.
Chuck
@Jian Lin: Also, there is no such thing as a "global" function. The default context (ie, "self" if you aren't inside the definition of a class, module, method, etc), is an object of type Object called "main". If you define a function without specifying what object to put it on, that's where it goes. (You can see this by opening up irb and executing `puts self`.)
John Hyland