tags:

views:

90

answers:

4

Hi,

I have a txt file which contains data in the following format:

X1 Y1

X2 Y2

etc..

I want to read the data from this file and create two lists in ruby (X containing X1, X2 and Y containing Y1, Y2). How can I do this in Ruby?

Thanks.

A: 

Something like this if you have exactly two columns:

one = Array.new
two = Array.new

File.open("filename") do |file|
   while line = file.gets
     one << line.split[0]
     two << line.split[1]
  end
end 
demas
+3  A: 

Pseudocode

File.new("source.txt", "r").each_line do |line|
  x, y = line.split
  xs << x
  ys << y
end

You might want to checkout the Rdoc for detail API.

DJ
+2  A: 

I prefer using the readlines method for things such as this.

x = []
y = []
File.readlines(filename).each do |line|
  x << line.split[0]
  y << line.split[1]
end

As Mladen (from the comments of this answer) suggests, I am splitting it twice which is probably slower than assigning it to a variable and referencing that. He also mentions that using foreach is better than readlines, and I agree. Using their advice, this is how we would both go about doing it:

x = []
y = []
File.foreach(filename).each do |line|
  line = line.split
  x << line[0]
  y << line[1]
end
Ryan Bigg
+1 - Very clean
Webbisshh
You could use `File.foreach(filename)` instead of `File.readlines(filename).each` and avoid loading whole file to memory. Also you are doing `split()` twice, which is not necessary.
Mladen Jablanović
Very true Mladen, you could also assign the split to a variable and use that.
Ryan Bigg
+8  A: 

A real one-liner:

x, y = File.foreach("filename").collect {|line| line.split}.transpose
glenn jackman