-
-
Save stevegraham/3753125 to your computer and use it in GitHub Desktop.
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
| def gen_times(factor) | |
| return Proc.new { |n| n * factor } | |
| end | |
| times3 = gen_times(3) | |
| times5 = gen_times(5) | |
| times3.call(12) #=> 36 | |
| times5.call(5) #=> 25 | |
| times3.call(times5.call(4)) #=> 60 |
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
| @proc = Proc.new { |a,b,c| puts [a,b,c].inspect } | |
| @lambda = lambda { |a,b,c| puts [a,b,c].inspect } | |
| @proc.call 1,2,3 | |
| # => [1,2,3] | |
| @lambda.call 1,2,3 | |
| # => [1,2,3] | |
| # Proc is chilled out. Proc just ignores any more arguments than it is expecting | |
| @proc.call 1,2,3,4,5,6,7,8 | |
| # => [1,2,3] | |
| # Procs also pass in nil in lieu of missing arguments | |
| @proc.call 1,2 | |
| # => [1, 2, nil] | |
| # lambda is not so chill | |
| @lambda.call 1,2,3,4,5,6,7,8 | |
| # => ArgumentError: wrong number of arguments (8 for 3) | |
| @lambda.call 1,2 | |
| # => ArgumentError: wrong number of arguments (2 for 3) |
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
| module Kernel | |
| def proc(&block) | |
| Proc.new &block | |
| end | |
| end |
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
| def proc_object | |
| obj = Proc.new { return 'returning from the proc' } | |
| obj[] | |
| return 'returning from the method body' | |
| end | |
| def lambda_object | |
| obj = lambda { return 'returning from the proc' } | |
| obj[] | |
| return 'returning from the method body' | |
| end | |
| proc_object | |
| #=> "returning from the proc" | |
| lambda_object | |
| #=> "returning from the method body" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment