Dexus Dexus - 1 year ago 66
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 =
IO.foreach("test.txt") do |line|
grab = line.chomp(" " + "/n").split
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 Source

If you want to consolidate this into a singular array:

grab = [ ]

IO.foreach("test.txt") do |line|

Another way:

grab = IO.readlines("test.txt").flat_map do |line|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download