当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

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
网友答案:

You should do something like

grab << line.chomp(" " + "/n").split
网友答案:

This gives you what you're looking for:

grab = IO.foreach("test2.txt").map {|line| line.split(/\D/) }.flatten
puts "#{grab}"

This produces the single array output:

["3", "5", "10", "2", "7", "15"]

It can all be wrapped up into a nice, tidy one-liner if you prefer it that way:

grab = IO.foreach("test2.txt").map {|line| line.split(/\D/) }.flatten
puts "#{grab}"

If you want to do an integer conversion in the process, you can modify the line.split to this:

grab = line.split(/\D/).map(&:to_i)

That change will produce this output:

[3, 5, 10, 2, 7, 15]
分享给朋友:
您可能感兴趣的文章:
随机阅读: