Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Proc#lambda?

prc.lambda? → true or false

Returns true if a Proc object is lambda. false if non-lambda.

The lambda-ness affects argument handling and the behavior of return and break.

A Proc object generated by proc ignores extra arguments.

Example
proc {|a,b| [a,b] }.call(1,2,3)    #=> [1,2]

It provides nil for missing arguments.

Example
proc {|a,b| [a,b] }.call(1)        #=> [1,nil]

It expands a single array argument.

Example
proc {|a,b| [a,b] }.call([1,2])    #=> [1,2]

A Proc object generated by lambda doesn’t have such tricks.

Example
lambda {|a,b| [a,b] }.call(1,2,3)  #=> ArgumentError
lambda {|a,b| [a,b] }.call(1)      #=> ArgumentError
lambda {|a,b| [a,b] }.call([1,2])  #=> ArgumentError

Proc#lambda? is a predicate for the tricks. It returns true if no tricks apply.

Example
lambda {}.lambda?            #=> true
proc {}.lambda?              #=> false

Proc.new is the same as proc.

Example
Proc.new {}.lambda?          #=> false

lambda, proc and Proc.new preserve the tricks of a Proc object given by & argument.

Example
lambda(&lambda {}).lambda?   #=> true
proc(&lambda {}).lambda?     #=> true
Proc.new(&lambda {}).lambda? #=> true

lambda(&proc {}).lambda?     #=> false
proc(&proc {}).lambda?       #=> false
Proc.new(&proc {}).lambda?   #=> false

A Proc object generated by & argument has the tricks

Example
def n(&b) b.lambda? end
n {}                         #=> false

The & argument preserves the tricks if a Proc object is given by & argument.

Example
n(&lambda {})                #=> true
n(&proc {})                  #=> false
n(&Proc.new {})              #=> false

A Proc object converted from a method has no tricks.

Example
def m() end
method(:m).to_proc.lambda?   #=> true

n(&method(:m))               #=> true
n(&method(:m).to_proc)       #=> true

define_method is treated the same as method definition. The defined method has no tricks.

Example
class C
  define_method(:d) {}
end
C.new.d(1,2)       #=> ArgumentError
C.new.method(:d).to_proc.lambda?   #=> true

define_method always defines a method without the tricks, even if a non-lambda Proc object is given. This is the only exception for which the tricks are not preserved.

Example
class C
  define_method(:e, &proc {})
end
C.new.e(1,2)       #=> ArgumentError
C.new.method(:e).to_proc.lambda?   #=> true

This exception ensures that methods never have tricks and makes it easy to have wrappers to define methods that behave as usual.

Example
class C
  def self.def2(name, &body)
    define_method(name, &body)
  end

  def2(:f) {}
end
C.new.f(1,2)       #=> ArgumentError

The wrapper def2 defines a method which has no tricks.

See also #inspect #parameters #hash #ruby2_keywords also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0