def one(arg)
if block_given?
"block given to 'one' returns #{yield}"
else
arg
end
end
def two
if block_given?
"block given to 'two' returns #{yield}"
else
"no block given to 'two'"
end
end
# ブロックはtwoに関連付けられる
result1 = one two {
"three"
}
# ブロックはoneに関連付けられる
result2 = one two do
"three"
end
result3 = one two
puts "With braces, result = #{result1}"
puts "With do/end, result = #{result2}"
puts "With no block, result = #{result3}"
出力結果:
With braces, result = block given to 'two' returns three
With do/end, result = block given to 'one' returns three
With no block, result = no block given to 'two'
関連