Ruby 临时变量赋值和修改
Ruby temporary variable assignment and modification
我有一个像 "hat" 这样的词,我想造一个完全相同但最后一个字母不同的新词。
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"
但是这两个词都变成了 had!
我有一种预感,这可能与指向内存中相同位置的两个变量有关?
为什么会这样,我怎样才能保留这两个值?
Why is this happening
你绝对应该阅读这篇文章 Is Ruby pass by reference or by value?
how can I keep both values?
使用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
我有一个像 "hat" 这样的词,我想造一个完全相同但最后一个字母不同的新词。
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"
但是这两个词都变成了 had!
我有一种预感,这可能与指向内存中相同位置的两个变量有关?
为什么会这样,我怎样才能保留这两个值?
Why is this happening
你绝对应该阅读这篇文章 Is Ruby pass by reference or by value?
how can I keep both values?
使用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