Is it possible to eliminate the temporary variable

L

Li Chen

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
 
T

Thairuby ->a, b {a + b}

Is this work?

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

Li Chen

Thairuby said:
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
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top