我是红宝石的新手,刚开始学习。无法找到从文件中读取二维数组中的方阵的解决方案。
file 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,0,0],[0,0,0,0,0,0,0], [0,0,0,0,15,0,0]]
答案 0 :(得分: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]]