Skip to content

Instantly share code, notes, and snippets.

/_.rb Secret

Created August 25, 2016 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1a94709ece0430ad87332fed148d5961 to your computer and use it in GitHub Desktop.
Save anonymous/1a94709ece0430ad87332fed148d5961 to your computer and use it in GitHub Desktop.
# The beginner is given this piece of code to wrangle
def foo1
lambda do |x|
lambda do |y|
lambda do |f|
f.call(x, y)
end
end
end
end
# Piece of cake: pass x, pass y, pass f
foo().call(5).call(6).call(lambda do |x,y|; x + y; end)
#=> 11
# Now the beginner is given this:
def foo2
lambda do |x|
lambda do |y|
yield(x, y)
end
end
end
# Piece of cake, pass x, then y, then block
foo().call(5).call(6) do |x,y|
x + y
end
#=> #<Proc:0x007f10ffccea18@(irb):160 (lambda)>
# Huh? But everyone says blocks are like functions. What happened?
# *Research*
foo2 do |baz,quux|
baz + quux
end.call(5).call(6)
#=> 11
# Tada!
# The *key* distinction in this case: blocks must be passed *upfront* to methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment