Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like "callable" in ruby?

Tags:

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):
    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?

like image 718
python Avatar asked May 05 '16 09:05

python


2 Answers

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"
like image 56
sawa Avatar answered Nov 03 '22 07:11

sawa


This syntax is not allowed in ruby out of the box. This is because parentheses might be omitted in function calls and ruby parser has no chance to understand that you are to call “callable” rather than just address it. The easiest workaround might be:

▶ λ = ->(param) { puts param }
#⇒ #<Proc:0x00000004e93050@(pry):7 (lambda)>
▶ λ.call(5) if λ.respond_to? :call
#⇒ 5

There is a specific corner case, ruby blocks. Everything, that responds to to_proc method, might be passed as code block to any method, that accepts code blocks, and the block will be called implicitly.

E.g.:

▶ [1,2,3].each &λ
#⇒ 1
#⇒ 2
#⇒ 3
like image 4
Aleksei Matiushkin Avatar answered Nov 03 '22 08:11

Aleksei Matiushkin