Search code examples
rubyfunctionirb

In Ruby, how to show or print out a function object, without invoking it?


Say, inside of irb if I do

def foo
  return 123
end
foo

it will give 123. That's because Ruby doesn't need the () to invoke the function. But how do I actually print out the function object? (kind of like in the JavaScript console, when I say function foo() {} and type foo, it will show foo as a function (object).)


Solution

  • You can use defined? for that:

    def foo
      return 123
    end
    foo
    #=> 123
    
    defined?(foo)
    #=> "method"
    

    A local variable would return:

    bar = 123
    #=> 123
    
    defined?(bar)
    #=> "local-variable"
    

    Or:

    def foo
      return 123
    end
    foo
    #=> 123
    
    method(:foo)
    #=> Object#foo()
    method(:foo).call
    #=> 123