From: Robert Klemme Date: 2010-01-22T17:33:13+09:00 Subject: Re: an elegant way to modify all lines from file by using map() function? 2010/1/21 Charles Oliver Nutter : > On Thu, Jan 21, 2010 at 4:20 PM, RobertGawron wrote: >> but in your language I didn't find the way to create in one step array >> of all lines from file, that could be used by map(). If I really want >> to use map in this situation I have to use secondary array (called >> arr) like in this snippet? >> >> arr = Array.new >> File.open('foo').each_line{ |l| arr.push l } >> p arr.collect{ |l| l.upcase } > > On 1.8.7+, you can use .lines to get an Enumerator: > > p File.open('foo').lines.map {|l| l.upcase} This does not close the file handle properly. I'd rather do something like this: File.foreach('foo').map {|l| l.upcase} File.foreach('foo').map(&:upcase) These have the advantage over some of the presented solutions that they do not create two large Arrays in memory but just one - the mapped version. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/