Created
November 25, 2012 18:19
-
-
Save rauchy/4144655 to your computer and use it in GitHub Desktop.
Blocks In-depth: Lambdas
This file contains 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
l = lambda { |first_name, last_name| puts "Hello, #{first_name} #{last_name}!" } | |
l.call("Omer", "Rauchwerger") # => Hello, Omer Rauchwerger! | |
l.call("Omer") # => ArgumentError: wrong number of arguments (1 for 2) | |
l.call("Omer", "Lachish", "Rauchwerger") # => ArgumentError: wrong number of arguments (3 for 2) |
This file contains 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 outside | |
puts "entering outside" | |
l = lambda { return } # l has invocation semantics | |
inside(l) | |
puts "exiting outside" | |
end | |
def inside(l) | |
puts "entering inside" | |
l.call | |
puts "exiting inside" | |
end | |
outside | |
# entering outside | |
# entering inside | |
# exiting inside | |
# exiting outside |
This file contains 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
foo = ->(name) { puts "Hello, #{name}" } | |
foo.call("Omer") |
This file contains 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
p = proc { |first_name, last_name| puts "Hello, #{first_name} #{last_name}!" } | |
p.call("Omer", "Rauchwerger") # => Hello, Omer Rauchwerger! | |
p.call("Omer") # => Hello, Omer ! | |
p.call("Omer", "Lachish", "Rauchwerger") # => Hello, Omer Lachish! |
This file contains 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 outside | |
puts "entering outside" | |
p = proc { return } # p has yield semantics | |
inside(p) | |
puts "exiting outside" | |
end | |
def inside(p) | |
puts "entering inside" | |
p.call | |
puts "exiting inside" | |
end | |
outside | |
# entering outside | |
# entering inside |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment