Created
February 21, 2009 19:08
-
-
Save caius/68141 to your computer and use it in GitHub Desktop.
Trying to explain the difference in how blocks "bind" to methods 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
def foo *args | |
p args | |
puts "foo: " + block_given?.to_s | |
return "foo" | |
end | |
def bar | |
puts "bar: " + block_given?.to_s | |
return "bar" | |
end | |
foo do | |
end | |
# no args | |
# block given | |
foo {} | |
# no args | |
# foo got block | |
foo bar {} | |
# args: "bar" | |
# foo didn't get block | |
# bar got block | |
foo bar do | |
end | |
# args: "bar" | |
# foo got block | |
# bar didn't get block | |
# Basically {} binds to the immediate method before it, | |
# do;end takes the easy option out and assumes the preceeding | |
# method is an argument. | |
# So if we rewrite the last two methods with brackets as | |
# ruby interprets it: | |
# Bar gets the block and | |
# foo gets all of that as an argument. | |
foo( bar {}) | |
# Foo gets both the block and bar as an argument. | |
foo( bar ) do | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment