tags:

views:

48

answers:

2

Noob question:

Consider the following C# code:

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

What would be the correspondent code in Ruby? The thing is that I want the return object of a class method to behave just like an Enumerable, so I can call include?, sort_by, etc. on it.

By the way, I know I can make the method return a list, but that wouldn't be (a) lazy, since the list would need to be calculated first, (b) looking for an ideomatic solution :-)

+2  A: 
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
sepp2k
Great answer, thanks. Any way to make recursive enumerations out of that solution, or would I need to use another .each/yield?
Hugo S Ferreira
A: 

Just fyi, the C# could be reduced to this, which is still lazy.

public IEnumerable<xpto> CalculatedList
{  get { return privateList.OfType<xpto>()); } }
David B
True :-) I did wanted to convey the use of yield, though.
Hugo S Ferreira