Ruby临时变量赋值和修改

时间:2015-03-17 22:14:01

标签: ruby variable-assignment

我有一个像“帽子”这样的词,我想创建一个完全相同的新词,但是后面的字母不同。

word = "hat"
temp = word
temp[temp.length-1] = "d"

puts "temp is #{temp}"
puts "word is #{word}"

# Output:
# temp is had
# word is had

我现在期望temp = "had"word = "hat",但这两个词都变了!

我有预感,这可能与指向内存中相同位置的两个变量有关吗?

为什么会发生这种情况,如何保留这两个值?

1 个答案:

答案 0 :(得分:2)

  

为什么会发生这种情况

您一定要阅读此Is Ruby pass by reference or by value?

  

我怎样才能保留这两个值?

使用dup。它会复制object

word = "hat"
temp = word.dup
temp[temp.length-1] = "d"

puts "temp is #{temp}"
puts "word is #{word}"

# Output:
# temp is had
# word is hat