我正在尝试像这样交换数组中的两个元素
deck = []
(deck << (1..52).to_a << 'A' << 'B').flatten!
p deck
deck[deck.index("A")], deck[deck.index("B")] = deck[deck.index("B")], deck[deck.index("A")] #swap "A" and "B"
p deck
但它没有交换。但是,如果我这样做:
deck[52], deck[53] = deck[53], deck[52]
它有效。有什么建议吗?
答案 0 :(得分:2)
为了简单起见,让甲板只是['A','B']。以下是逐步评估:
deck = ['A', 'B']
deck[deck.index("A")], deck[deck.index("B")] = deck[deck.index("B")], deck[deck.index("A")] # deck == ['A', 'B']
deck[deck.index("A")], deck[deck.index("B")] = deck[1], deck[0] # deck == ['A', 'B']
deck[deck.index("A")], deck[deck.index("B")] = 'B', 'A' # deck == ['A', 'B']
deck[0], deck[deck.index("B")] = 'B', 'A' # deck == ['A', 'B']
# Applying first assignment.
..., deck[deck.index("B")] = ..., 'A' # deck == ['B', 'B']
# NOTE: deck.index("B") is 0 now, not 1!
..., deck[0] = ..., 'A' # deck == ['B', 'B']
# Applying second assignment.
... # deck == ['A', 'B']
所以你的代码实际上只是在为数组的相同元素提供twise。
要解决此问题,只需将deck.index()值保存到临时数组:
deck = []
(deck << (1..52).to_a << 'A' << 'B').flatten!
p deck
index_a, index_b = deck.index("A"), deck.index("B")
deck[index_a], deck[index_b] = deck[index_b], deck[index_a]
p deck