From: Robert Klemme Date: 2011-12-09T18:18:02+09:00 Subject: Re: reading from file without end-of-lines On Fri, Dec 9, 2011 at 9:58 AM, Gavin Sinclair wrote: >> i'm trying to read a few text values from single file: >> >>  if File.exists?(file) >>      File.open(file, 'r+') do |f| >>        value1 = f.gets.strip >>        value2 = f.gets.strip >>        value3 = f.gets.strip >>        value4 = f.gets.strip >>      end >>    end >> >> each value is stored in separate line and 'strip' above is used only to >> get rid of end-of-line characters. is there any easier way to do the same? You could start by not defining individual variables with indexed names but using an array. > I tend to strip out all such characters at once, before operating on any line. > >  File.readlines(file).map { |line| line.strip }.each do |line| >    ... >  end > > In your case, I guess that would be > >  lines = File.readlines(file).map { |line| line.strip } >  value1 = lines.shift >  value2 = lines.shift >  # etc. >  # or >  v1, v2, v3, v4 = lines.shift(4) Executing File.readlines completely is inefficient if the file is large and only the first four lines are needed. One could do values = File.open(file) do |f| f.first(4).map! &:strip! end Or even shorter values = File.foreach("cl").first(4).map! &:strip! If there are proper names for variables one can do name, street, zip, city = File.foreach("cl").first(4).map! &:strip! ;-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/