【问题标题】:Ruby temporary variable assignment and modificationRuby临时变量赋值和修改
【发布时间】:2015-03-17 22:14:00
【问题描述】:

我有一个像“帽子”这样的词,我想造一个完全一样的新词,但最后一个字母不同。

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!

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

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

【问题讨论】:

  • 您还可以将String#sub 与正则表达式一起使用:'hat'.sub(/.$/,'d') #=> 'had'。这不会改变"hat"

标签: ruby variable-assignment


【解决方案1】:

为什么会这样

你一定要读这个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 2015-09-19
    • 2011-10-11
    • 2014-03-11
    • 2018-02-24
    • 2016-12-19
    相关资源
    最近更新 更多