我在寫一些從文件讀取輸入的代碼。二維數組不應該被覆蓋
我的代碼解析輸入文件的內容並將數據存儲爲二維數組,例如,
的輸入(請參閱下面的正確的格式輸入文件,我不能格式化在這裏工作):
ABC
DEF
摹
解析2D數組後應該看起來像這樣... [['A 」, 'B', 'C'],[ 'd', 'E', 'F'],[ 'G']]
我的問題是,在某種程度上先前元素被寫在在二維數組中有後續的條目,例如
[ 'G'],[ 'G'],[ 'G']
我已經通過它看上去卻無法看到這是如何發生的,因爲寫入二維數組應每個新條目只會出現一次,然後它們只能在將新數據附加到二維數組時纔會發生,而不會覆蓋以前的條目。
我有點卡住了,你們有沒有任何想法,爲什麼會發生這種情況?
謝謝!:)
代碼
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
嘿@tadman,謝謝你的輸入。我只是使用'p'作爲快速的方式來拋出數組的內容。再次感謝您看這個:) – TheLemonSong