Ruby 的 block 是個不錯的設計. 一個 block 就是一些程式碼, 其 context 為正在動態執行的環境. 有點像是一般稱為 callback 機制, 但 block 方法精巧多了
當你呼叫 method 時, 你可以給它一個 block. 下面 “each” 是 method, do ~ end 中間就是 block, |x|, x 就是傳給 block 的參數.
books = ["Ruby", "Rails"]
books.each do |b|
puts b
end
那麼 method 裡如何執行 block? 利用 “yield”
def three_times
for i in 1..3 do
yield i
end
end
#invoke
three_times do |i|
puts "#{i}, see you!"
end
那要是你的 method 不論有沒有 block 都可以接受的話, 你就要用 block_given? 來測試
class File
def self.my_open(*args)
result = f = File.new(*args)
if block_given?
result = yield f
f.close
end
return result
end
end
File.my_open("x.txt", "w") { |f|
f.puts "Hello World!"