试图用绳子理解铲子操作员

时间:2017-10-19 19:03:31

标签: ruby string

我正在经历http://rubykoans.com/

在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?

我错过了什么?

1 个答案:

答案 0 :(得分:1)

设置hi = original_string时,hi变量只是指向同一对象的新变量。如果您查看hi.object_idoriginal_string.object_id,您会发现它们是相同的。如果你想要一个对象的克隆,你可以操纵而不影响 original_string,您需要说hi = original_string.clonehi = original_string.dup之类的内容。