Reputation: 6573
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)
Upvotes: 27
Views: 12231
Reputation: 731
Actually you can check if variable is_a?
a Proc
x = (lambda {})
x.is_a?(Proc) # true
Upvotes: 4
Reputation:
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.
Upvotes: 45