我想在Ruby中的塊中指定規則(在這個例子中,規則定義是「好」還是「壞」)的DSL。下面是一個(非常簡化的版本),我想做的事:從塊返回 - 從塊內調用的方法?
def test_block
# Lots of other code
is_good = yield # ... should give me true or false
# Lots of other code
end
test_block do
good if some_condition
good if some_other_condition
bad
end
有什麼辦法,我可以定義方法good
和bad
,使該塊休息時間嗎?在上面的例子中,我想:
- 檢查,如果some_condition是真實的,如果是,打出來的塊,並將它返回true
- 檢查,如果some_other_condition是真實的,如果是這樣,打出來的塊,並將它返回true
- 回報從塊假無條件如果我們仍然在它
即我要讓上面的代碼的行爲,就好像我有writt恩,像這樣的塊:
result = test_block do
break true if some_condition
break true if some_other_condition
break false
end
在好/壞方法的定義把break
顯然是行不通的。有沒有其他方法可以達到我想要的效果,還是應該考慮採取一些完全不同的方法來實現這一目標?
非常相關:http://innig.net/software/ ruby/closures-in-ruby.rb – 2010-11-17 18:39:17