2009-08-17 46 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