Determine if a parameter/variable is a ("is_a?") lambda?
Solution 1
A block is not a lambda. To see if there is a block use block_given?
.
In any case, I would use "responds to call" if and only if I really needed this construct, which I would try to avoid. (Define the contract and make the caller responsible for invoking it correctly!)
(lambda {1}).respond_to? :call # => true
(1).respond_to? :call # => false
I believe this form of structural (aka duck) typing is more inline with Ruby than nominative typing with "is a" relationships.
To see what "is a" relationships might hold (for future playing in a sandbox):
RUBY_VERSION # => 1.9.2
(lambda {}).class # => Proc
(Proc.new {}).class # => Proc
def x (&p); p; end # note this "lifts" the block to a Proc
(x {}).class # => Proc
Happy coding.
Solution 2
Actually you can check if variable is_a?
a Proc
x = (lambda {})
x.is_a?(Proc) # true
Related videos on Youtube
mbdev
In my free time I am developing side projects to experiment with new technologies using NodeJS, AngularJS, Ansible, Redis, Rails and MongoDB. See github projects: https://github.com/mb-dev?tab=activity
Updated on June 27, 2022Comments
-
mbdev almost 2 years
How to check if a given parameter is a lambda?
def method(parameter) if ??? puts "We got lambda" parameter.call else puts "I did not get a block" end end method(lambda { 1 }) method(1)
-
Automatico over 10 yearsVery cool that there is a
respond_to?
method. Makes these sorts of things a lot easier.