Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 二维数组中文件的方阵_Ruby - Fatal编程技术网

Ruby 二维数组中文件的方阵

Ruby 二维数组中文件的方阵,ruby,Ruby,我是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

我是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
结果:

[[“03 00 10 0”]、[“09 0 0 0 0”]、[“03 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 0 0 15 0”]

需要结果:

[[0,3,0,0,0,10,0,0,0],[0,0,9,0,0,0,0,0,0,0,0,0,0,0,15],[0,0,0,0,0,0,0,0,0,0,8,0],[0,0,0,0,0,0,0,0,0,0,0,0,15,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]]