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.
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.
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
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.
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
A real one-liner:
x, y = File.foreach("filename").collect {|line| line.split}.transpose