On 09.02.2007 15:39, Bharat Ruparel wrote:
> Thanks Robert,
> Tim Hunter's solution seems most straightforward to me.  Which is:
> counter = 1
> IO.foreach("test.txt") {|line| puts "#{counter}. #{line}"; counter += 1}
> 
> The solution that you present:
>  require 'enumerator'
>  IO.to_enum(:foreach, "test.txt").inject(0) do |counter, line|
>     puts "#{counter}. #{line}"
>     counter + 1
>  end
> 
> Seems like a good one too, except more indirect.  When would you 
> recommend using one over another?  Or is it largely a matter of taste? 

Yes.  And there is a ton of other equally good solutions.

> Also, why do you have to "require" the enumerator module here whereas 
> Tim's solution didn't.

Because the module is not loaded by default.  (IIRC that will change / 
has changed in Ruby 1.9).

 > I did a search on "ri IO" and it shows that IO
> includes enumerable (it is not enumerator, I know).  Also it shows that 
> foreach is a class method for IO class whereas I could not find anything 
> on to_enum.  Is there a way to get RoR style online API docs for Ruby? 
> I find "ri" a bit primitive.

I usually use http://www.ruby-doc.org/

For example

http://www.ruby-doc.org/core/classes/Enumerable/Enumerator.html

Kind regards

	robert