Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a parameter/variable is a ("is_a?") lambda?

Tags:

ruby

lambda

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.


Actually you can check if variable is_a? a Proc

x = (lambda {})
x.is_a?(Proc) # true