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?
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With