(1)根據(jù)約定葡幸,單行block用大括號包圍剖笙,多行block用do...end包圍
(2)block放在方法調(diào)用的參數(shù)之后:方法名 + (參數(shù)) + block
(3)在方法中,可以使用yield
調(diào)用block中的代碼。執(zhí)行完后再返回方法中瞧捌,執(zhí)行yield
的下一行。block和方法可以想象成協(xié)同例程润文,它們之間來回轉(zhuǎn)換控制權(quán)姐呐。
(4)yield
可以帶參數(shù)調(diào)用,block的形參用豎線包圍典蝌,yield('hello',99)
曙砂,{|str, num| ...}
例如:
def call_block
puts 'begin method'
yield
yield
puts 'end method'
end
call_block {puts 'in the block'}
輸出:
begin method
in the block
in the block
end method
例如:
animals=%w{ant bee cat dog}
animals.each {|animal| puts animal}
輸出:
ant
bee
cat
dog
其中each方法的偽代碼定義如下:
#在Array類中
def each
for each element #無效的偽代碼
yield(element)
end
end