2009-08-17 44 views
0

noob問題:IEnumerable的關於Ruby

考慮下面的C#代碼:

public IEnumerable<xpto> CalculatedList { 
    get { foreach(var item in privateList.OfType<xpto>()) yield return item; } 
} 

什麼是Ruby中對應的代碼?事情是,我想要一個類方法返回對象的行爲就像一個枚舉的,所以我可以調用包括?sort_by等就可以了。順便說一句,我知道我可以讓該方法返回一個列表,但這不會(懶),因爲列表需要首先計算,(b)尋找一個意識解決方案: - )

回答

2
require 'enumerator' 
def calculated_list 
    return enum_for(:calculated_list) unless block_given? 

    private_list.each do |item| 
    yield item.to_xpto # Or whatever the equivalent for OfType<xpto> looks like 
    end 
end 
+0

偉大的答案,謝謝。任何方式進行遞歸枚舉出該解決方案,否則我就需要使用另一個。每次/收益呢? – 2009-08-17 17:52:01

0

只是fyi,C#可以減少到這個,這仍然是懶惰的。

public IEnumerable<xpto> CalculatedList 
{ get { return privateList.OfType<xpto>()); } } 
+0

真正:-)我也想傳達的使用收益率,雖然。 – 2009-08-17 20:32:42