Friday, April 2, 2010

lambda

Although they aren’t as common as blocks in ruby, I’ve been encountering some lambda usages, and usually find myself proper confused. This is undoubtedly because I have an incomplete understanding of closures, which goes something like this: I think of a closure as a bit of code that has a shorter lifespan than the variables it accesses. I understand blocks to be closures that are defined in the context of a method call, and by comparison, lambdas seem to be closures that are not dependent on a method call, but can rather be simply stated, assigned to a variable, or executed on the spot. You can explicitly pass a lambda as a block to a method like this:

my_block = lambda {|x| puts x}
some_method(&my_block)

Where my understanding gets especially fuzzy is how lambdas differ from procs - from what I can tell, “lambda” is *nearly* equivalent to “Proc.new”, except that it handles returns differently, as seen in the ruby example on Wikipedia's closure page.
I’d like to see some useful applications of lambda, maybe this would help me "get it." So far, the most common usage of lambda that I’ve seen in the last few weeks is in rspec tests to do something like this:

it “should create a new customer entry” do
lambda do
make_new_customer(“John Doe”)
end.should change(Customer, :count).by(1)
end

which conveniently allows you to check that the count of your Customers changed without having to explicitly offload the count, call the method, and then check it again. (The rspec matcher “change” evaluates the provided value before and after the lambda.) For now, I'll keep my eyes out for more lambdas.

No comments:

Post a Comment