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