Ruby does great stuffs with closure, like in array iteration we are using closures in everywhere.
Ruby has 4 type of closures - Block, Procs, Lambda and Method. I'm trying to explain them in brief.
Block
It's used with '&' sign prefixed variable also executes using yield or *.call.
1 2 3 4 5 6 7 | def do_something_with(&block) puts "I did this with block using #{block.call}" end do_something_with {"ruby"} #=> I did this with block using ruby |
Procs (Procedures)
Its used as other ruby data types (array, hash, string, fixnum etc..), it's reusable and could be used across multiple calls. also several procedures could be passed at a time.
1 2 3 4 5 6 7 | def do_something_with(block) puts "I did this with Proc using #{block.call}" end do_something_with Proc.new { "ruby" } #=> I did this with Proc using ruby |
Also there is another difference between lambda and Proc. Proc's "return" will stop method and will return from Proc on the other hand lambda‘s "return" will only return it's own value to the caller method.
1 2 3 4 | l = lambda {|a, b| ...} l.call('A') #=> Error need to pass 2 arguments |
Example
1 2 3 4 5 6 7 | def who_win_the_title? l = Proc.new { return "Rafael Nadal" } l.call return "Roger Federer" end #=> "Rafael Nadal" |
Method
Method is another way around in ruby to use existing method as closure.
1 2 3 4 5 6 7 8 9 10 11 | def cheese puts 'cheese' end def say_cheese(block) block.call end say_cheese method(:cheese) #=> cheese |
I learned it from hear - http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/