Created
November 17, 2014 23:36
-
-
Save launchkit-codes/326ab358353916e053fe to your computer and use it in GitHub Desktop.
Difference between Procs, Blocks, Lambdas in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # Main difference: Procs are objects, blocks are not. | |
| # | |
| # The '&' tells ruby to turn the proc into a block. | |
| # | |
| class Array | |
| def map2 | |
| new_ary = [] | |
| self.each do |elem| | |
| new_ary << yield(elem) | |
| end | |
| new_ary | |
| end | |
| end | |
| p = Proc.new {|elem| elem * 2} | |
| # If you omit '&' an error will be raised | |
| # because the method expect to receive a block. | |
| p([1,2,3].map2(&p)) # => [2, 4, 6] | |
| p([1,2,3].map2 {|elem| elem * 3}) # => [3, 6, 9] | |
| # Difference between procs and lambdas. | |
| # Both are Proc object. The difference is | |
| # shown when returning the objects | |
| p Proc.new {'foo'} # => #<Proc:0x000001030a3ad0@proc_and_block.rb:24> | |
| p lambda {'bar'} # => #<Proc:0x000001018cba20@proc_and_block.rb:25 (lambda)> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment