0

我是ruby的新手,刚开始学习。找不到从文件中读取二维数组中的方阵的解决方案。

文件graph.txt:

0 3 0 0 10 0 0
0 0 9 0 0 0 0
0 0 0 3 0 0 15
0 0 0 0 0 0 10
0 0 0 0 0 8 0
0 0 0 0 0 0 0
0 0 0 0 15 0 0

我的代码:

n=7
Arr = Array.new(n).map!{Array.new(n)}
text = ''
tx = File.readlines("graph.txt")
text = tx.join
i=0
text.each_line do |line|
        Arr[i] = line.split(/\n/)
        i+=1
end

p Arr

结果:

[["0 3 0 0 10 0 0"], ["0 0 9 0 0 0 0"], ["0 0 0 3 0 0 15"], ["0 0 0 0 0 0 10"], [ "0 0 0 0 0 8 0"], ["0 0 0 0 0 0 0"], ["0 0 0 0 15 0 0"]]

需要结果:

[[0, 3, 0, 0, 10, 0, 0], [0, 0, 9, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 15], [ 0, 0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0, 8, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 15, 0, 0]]

4

1 回答 1

0
# Replace DATA.each_line with IO.readlines('graph.txt') to use the file as a data source

matrix = DATA.each_line.map { |line| line.split.map(&:to_i) }
puts matrix.inspect


__END__
0 3 0 0 10 0 0
0 0 9 0 0 0 0
0 0 0 3 0 0 15
0 0 0 0 0 0 10
0 0 0 0 0 8 0
0 0 0 0 0 0 0
0 0 0 0 15 0 0

# => [[0, 3, 0, 0, 10, 0, 0], [0, 0, 9, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 15], [0, 0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0, 8, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 15, 0, 0]]
于 2012-11-19T13:06:58.473 回答