我覺得我錯過了非常非常基本的東西,所以爲了避免撕掉更多的頭髮,我來這裏問爲什麼p1,p1t和p1t2正在用「hand = newgame」進行修改。查看p1「。我甚至不知道爲什麼P1會被修改,所以我在這裏完全困惑。任何幫助將非常感激。變量的基本問題
# encoding: utf-8
class Cards
def view hand
x = 0
hand.each do |card|
if card[0] == 's'
card[0] = '♠'
elsif card[0] == 'd'
card[0] = '♦'
elsif card[0] == 'h'
card[0] = '♥'
elsif card[0] == 'c'
card[0] = '♣'
else
#nil
end
hand[x] = card
x = x + 1
end
prettyhand = ''
hand.each do |card|
prettyhand = prettyhand + card[0] + card[1] + ' '
end
return prettyhand
end#view
end#Cards
###########
deck = 0
up = 0
p1 = 0
p2 = 0
newgame = Cards.new
p1 = [["c", "4"], ["s", "4"], ["d", "q"], ["c", "8"], ["s", "5"], ["s", "q"], ["h", "3"], ["c", "10"]]
p1t = []
p1t2 = []
hand = ''
p1.each do |card|
p1t.push card
end
p1t.each do |card|
p1t2.push card
end
p '----------------------------------'
p 'fresh p1:'
p p1
p p1t
p p1t2
hand = newgame.view p1
p 'unfresh p1:'#why is this changing??
p p1
p p1t
p p1t2
p '----------------------------------'
輸出:
"----------------------------------"
"fresh p1:"
[["c", "4"], ["s", "4"], ["d", "q"], ["c", "8"], ["s", "5"], ["s", "q"], ["h", "3"], ["c", "10"]]
[["c", "4"], ["s", "4"], ["d", "q"], ["c", "8"], ["s", "5"], ["s", "q"], ["h", "3"], ["c", "10"]]
[["c", "4"], ["s", "4"], ["d", "q"], ["c", "8"], ["s", "5"], ["s", "q"], ["h", "3"], ["c", "10"]]
"unfresh p1:"
[["♣", "4"], ["♠", "4"], ["♦", "q"], ["♣", "8"], ["♠", "5"], ["♠", "q"], ["♥", "3"], ["♣", "10"]]
[["♣", "4"], ["♠", "4"], ["♦", "q"], ["♣", "8"], ["♠", "5"], ["♠", "q"], ["♥", "3"], ["♣", "10"]]
[["♣", "4"], ["♠", "4"], ["♦", "q"], ["♣", "8"], ["♠", "5"], ["♠", "q"], ["♥", "3"], ["♣", "10"]]
"----------------------------------"
特別是,請注意,這也適用於方法調用。因此你的Cards#view方法修改了它的參數。 – 2012-04-19 01:38:09
我想我明白了!那麼,這裏最好的解決方案是什麼?我應該將數組轉換爲字符串來複制它們嗎?謝謝! – catbat 2012-04-19 01:42:22
@catbat:查看我的更新回答 – 2012-04-19 01:46:41