yield用法
在方法中使用yield來執行匿名函式
def call_block
puts "start"
yield
yield
puts "end"
end
# call_block {puts "blocks is cool"}
call_block do
puts "blocks is cool"
end
帶引數的code block
def call_block
yield(1)
yield("jelly")
end
call_blcok do |x|
puts "#{x} hello"
end
將匿名函式轉成類
def call_block(&block)
block.call(1)
block.call(2)
end
call_block do |x|
puts "#{x}: cool"
end
本作品採用《CC 協議》,轉載必須註明作者和本文連結