Last active
September 23, 2015 22:24
-
-
Save mwlang/29e7899e5e971985b39d to your computer and use it in GitHub Desktop.
Thought experiment to understand blocks and arguments better.
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
class Foobar | |
def to_s | |
"wah, wah" | |
end | |
end | |
@foobar = Foobar.new | |
def baz who, foobar | |
puts [who, foobar].join " says " | |
end | |
def foo *args, &block | |
@who = args.first || "default" | |
puts block_given?.inspect | |
puts instance_variables.inspect | |
if block_given? | |
yield(@foobar) | |
else | |
baz @who, "NO BLOCK" | |
end | |
end | |
puts "---- foo" | |
foo | |
puts "----- foo :bar" | |
foo :bar | |
puts "----- foo :bar do" | |
foo :bar do | |
baz @who, "nada" | |
end | |
puts "----- foo do" | |
foo do | |
baz @who, "zippo" | |
end | |
puts "----- foo :bar do |x|" | |
foo :bar do |x| | |
baz @who, x | |
end | |
puts "----- foo do |x|" | |
foo do |x| | |
baz @who, x | |
end |
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 | |
false | |
[:@foobar, :@who] | |
default says NO BLOCK | |
----- foo :bar | |
false | |
[:@foobar, :@who] | |
bar says NO BLOCK | |
----- foo :bar do | |
true | |
[:@foobar, :@who] | |
bar says nada | |
----- foo do | |
true | |
[:@foobar, :@who] | |
default says zippo | |
----- foo :bar do |x| | |
true | |
[:@foobar, :@who] | |
bar says wah, wah | |
----- foo do |x| | |
true | |
[:@foobar, :@who] | |
default says wah, wah |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment