On Fri, Dec 9, 2011 at 9:58 AM, Gavin Sinclair <gsinclair / gmail.com> wrote:
>> i'm trying to read a few text values from single file:
>>
>> =A0if File.exists?(file)
>> =A0 =A0 =A0File.open(file, 'r+') do |f|
>> =A0 =A0 =A0 =A0value1 =3D f.gets.strip
>> =A0 =A0 =A0 =A0value2 =3D f.gets.strip
>> =A0 =A0 =A0 =A0value3 =3D f.gets.strip
>> =A0 =A0 =A0 =A0value4 =3D f.gets.strip
>> =A0 =A0 =A0end
>> =A0 =A0end
>>
>> 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 sam=
e?

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.
>
> =A0File.readlines(file).map { |line| line.strip }.each do |line|
> =A0 =A0...
> =A0end
>
> In your case, I guess that would be
>
> =A0lines =3D File.readlines(file).map { |line| line.strip }
> =A0value1 =3D lines.shift
> =A0value2 =3D lines.shift
> =A0# etc.
> =A0# or
> =A0v1, v2, v3, v4 =3D 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 =3D File.open(file) do |f|
  f.first(4).map! &:strip!
end

Or even shorter

values =3D File.foreach("cl").first(4).map! &:strip!

If there are proper names for variables one can do

name, street, zip, city =3D File.foreach("cl").first(4).map! &:strip!

;-)

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/