Skip to content

Instantly share code, notes, and snippets.

@rauchy
Created November 25, 2012 18:19
Show Gist options
  • Save rauchy/4144655 to your computer and use it in GitHub Desktop.
Save rauchy/4144655 to your computer and use it in GitHub Desktop.
Blocks In-depth: Lambdas
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)
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
foo = ->(name) { puts "Hello, #{name}" }
foo.call("Omer")
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!
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