【发布时间】:2018-03-01 19:36:10
【问题描述】:
我正在编写一些从文件中读取输入的代码。
我的代码解析输入文件的内容并将数据存储为二维数组,例如
输入是(请参阅下面的输入文件以了解正确的格式,我无法在此处进行格式设置):
ABC
防御
G
解析后的二维数组应该是这样的... [['A','B','C',],['D','E','F'],['G']]
我遇到的问题是,以前的元素以某种方式被写入二维数组中,并带有后续条目,例如
[['G'],['G'],['G']]
我已经查看了它,但看不到这是如何发生的,因为对 2D 数组的写入应该只在每个新条目发生一次,然后它们应该只在将新数据附加到 2D 数组时发生,并且不覆盖以前的条目。
我有点卡住了,你们中有人知道为什么会这样吗?
谢谢!:)
代码
class Reader
def initialize
@command_array = Array.new { Array.new } # 2D array
end
def run(file)
return puts "please provide correct file" if file.nil? || !File.exists?(file)
command_line = Array.new #Temp array
p "----------------------------------------------------------------"
File.open(file).each do |line|
p "looking at a line of commands..."
line.split(' ').each do |command|
p "storing the command #{command} in temp array"
command_line.push(command)
p command_line
end
p "Storing the temp array as an element in the 2d array..."
@command_array.push(command_line)
p @command_array
p "Clearing the temp array..."
p "----------------------------------------------------------------"
command_line.clear
end
end
end
#
输入文件
A B C
D E F
G
#
输出
"looking at a line of commands..."
"storing the command A in temp array"
["A"]
"storing the command B in temp array"
["A", "B"]
"storing the command C in temp array"
["A", "B", "C"]
"Storing the temp array as an element in the 2d array..."
[["A", "B", "C"]]
"Clearing the temp array..."
"----------------------------------------------------------------"
"looking at a line of commands..."
"storing the command D in temp array"
["D"]
"storing the command E in temp array"
["D", "E"]
"storing the command F in temp array"
["D", "E", "F"]
"Storing the temp array as an element in the 2d array..."
[["D", "E", "F"], ["D", "E", "F"]]
"Clearing the temp array..."
"----------------------------------------------------------------"
"looking at a line of commands..."
"storing the command G in temp array"
["G"]
"Storing the temp array as an element in the 2d array..."
[["G"], ["G"], ["G"]]
"Clearing the temp array..."
#
【问题讨论】:
-
p x用于调试,相当于puts x.inspect。您应该使用puts显示提示,这样可以避免使用引号。 -
嘿@tadman,感谢您的意见。我只是使用“p”作为将数组内容扔到屏幕上的快速方法。再次感谢您查看此内容:)
标签: arrays ruby multidimensional-array