python python - 9 months ago 32
Ruby Question

Is there something like "callable" in ruby?

In python, I could use "callable" to check if a variable could be called or not. like this:

# -*- coding: utf-8 -*-

def test():
print "hello world"

a = test
if callable(a):

so in this way, I can tell that a is a function, not an instance variable.
But in ruby, the braces could be omitted, so for me, when I called it, I cannot tell if it is a function or instance variable. Is there some method to check if the variable is a function or instance variable at runtime?


Yes. defined? gives you what is being called.

a = 1
def a; end
b = 1
def c; end

defined? a   # => "local-variable"
defined? a() # => "method"
defined? b   # => "local-variable"
defined? c   # => "method"