Is it possible to eliminate the temporary variable

Hi all,

I use the following script to read a file and create a 2D array.
What bothers me is that I have to use a temporary variable. I wonder if
there is a better way to read a file and create a 2D array.

Thanks,

Li

##################

create a 2D array

def file_process
@data=[ ]

read in the file line by line

File.open(@file) do |a_file|
temp=[]
a_file.each_line do|a_line|
a_line.chomp!# remove \n
temp=a_line.split(/\t/) # tab is the separator
@data << temp
temp=[]
end
end
end

Is this work?

def file_process
@data=[]
File.foreach(@file) {|a_line| @data << a_line.chomp.split(/\t/)}
end

Thairuby ->a, b {a + b} wrote:

Is this work?

def file_process
@data=[]
File.foreach(@file) {|a_line| @data << a_line.chomp.split(/\t/)}
end

Yes, it works and thank you so much.

Li

On 09/27/2009 07:31 PM, Thairuby ->a, b {a + b} wrote:

Is this work?

def file_process
@data=[]
File.foreach(@file) {|a_line| @data << a_line.chomp.split(/\t/)}
end

In 1.9 you can do

@data = File.foreach(file_name).map {|l| l.chomp.split /\t/}

In 1.8 you’ll need something like

require ‘enumerator’
@data = File.enum_for(:foreach, file_name).map {|l| l.chomp.split /\t/}

or this which should work in both

@data = File.readlines(file_name).map {|l| l.chomp.split /\t/}

Kind regards

robert