The Ruby documentation for the lambda method (a.k.a. proc) says “Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.” This is almost exactly right. There are, however, at least two cases where this turns out to be false.

The first is when the block passed to lambda does not have an argument list specified. The resulting Proc object will not check arguments in this case.


  def test_lambda_checks_arguments
    l = lambda {||}
    assert_raises(ArgumentError) {l.call(1)}
  end

  def test_lambda_doesnt_check_arguments_if_no_arguments_specified
    l = lambda {}
    assert_nothing_raised {l.call(1)}
  end

The two tests above prove that Proc#call doesn’t check arguments for a lambda proc with no arguments unless you specify that the proc takes no arguments by including an empty parameter list. This is not the only case where argument checking is not done for lambda procs, however.

If you pass a lambda proc to a method is a block (using &), this circumvents the argument checking that would normally take place, even when you specify a blank argument list.


  def test_lambda_doesnt_check_arguments_when_yielded_to_even_if_arguments_specified
    l = lambda {||}
    def yield_1_to; yield 1; end
    assert_nothing_raised {yield_1_to &l}
  end

The above test passes, even though one argument is yielded to a lambda proc that explicitly takes no args. I haven’t read the source yet, but my guess about what’s happening here is that Ruby converts the proc back to a normal block. Since blocks normally don’t check arguments, there’s no reason to expect the one here to either. Nonetheless, the result surprised me until I thought about it longer.

I categorize this as one of those Ruby oddities that for the most part doesn’t hurt you in practice. I don’t recall ever having run into a bug or debugging issue where not knowing about this hindered me. I do think that building knowledge about oddities like these is good practice though. It deepens your knowledge of Ruby in general, and every so often one small bit of knowledge will save you a chunk of time.

Sorry, comments are closed for this article.