Ruby Block

1、用於迭代器之後
Ruby的迭代器與其他語言的迭代器很不相同,它的迭代器一般都是函數,如:

def three_times
yield
yield
yield
end

使用實例: three_times { puts “hello”}
Ruby內置了一些迭代器如find,each,collect,inject等
3.times { puts “hello” }
[‘1’,’2’,’3’].find {|item| item == ‘1’}
2、事務block
使用block可以形成事務機制,使得事務能夠根據一定的步驟執行,如:

class File
def File.open_and_process(*args)
f = File.open(*args)
yield f
f.close()
end
end

上面這段代碼是一個打開文件–> 操作 –> 關閉文件的事務
File.open_and_process("testfile","r") do |file|
while line = file.gets
puts line
end
end

3、Block作爲閉包
class Button
def initialize(lable,&action)
super(label)
@action = action
end
def button_pressed
@action.call(self)
end
end

start_button = Button.new(“Start”) { function1 }
pause_button = Button.new(“Pause”) { function2}
在定義方法時,在最後一個參數前加一個&,那麼當調用該方法時,Ruby會尋找一個block。block將會
初始化爲一個Proc的對象,此時就可以使用Proc#call方法調用相應的block。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章