在koans / about_strings.rb:100文件中
def test_the_shovel_operator_modifies_the_original_string
original_string = "Hello, "
hi = original_string
there = "World"
hi << there
assert_equal "Hello, World", original_string
# THINK ABOUT IT:
#
# Ruby programmers tend to favor the shovel operator (<<) over the
# plus equals operator (+=) when building up strings. Why?
end
虽然我认为 original_string 等于“Hello”,而 hi 等于“Hello,World”
我看到这张海报有类似的问题,但不完全是:
Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?
我错过了什么?
答案 0 :(得分:1)
设置hi = original_string
时,hi
变量只是指向同一对象的新变量。如果您查看hi.object_id
和original_string.object_id
,您会发现它们是相同的。如果你想要一个对象的克隆,你可以操纵而不影响
original_string
,您需要说hi = original_string.clone
或hi = original_string.dup
之类的内容。