Dexus Dexus - 6 months ago 13
Ruby Question

When I try to make an array in Ruby from a file, it makes multiple arrays

sorry if this is a simple solution, but I'm trying to grab all the numbers from a file into an array. The file I'm importing reads

3 5 10
2 7 15


This is my code

grab = Array.new
IO.foreach("test.txt") do |line|
grab = line.chomp(" " + "/n").split
end
p grab


When I do this, it prints the last line of numbers, yet when I print it from the IO block, it prints 2 arrays. First and second line.

Answer

If you want to consolidate this into a singular array:

grab = [ ]

IO.foreach("test.txt") do |line|
  grab.concat(line.chomp.split)
end

Another way:

grab = IO.readlines("test.txt").flat_map do |line|
  line.chomp.split
end