2017-10-19 40 views
0

我經歷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將等於「你好」,那將等於「你好,世界」

我看到這個海報有一個類似的問題,但不是很:

Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?

我在想什麼?

+1

誰創造了術語「鏟運營商」? – Stefan

+0

我不知道我見過用於連接字符串的鏟運算符。一些更常用的技術是'「#{hi}#{there}」或'[hi,there] .join'。 – moveson

+0

再次看第3行:在第3行中,*告訴* Ruby使*它們相同!因此,他們*是相同的。 –

回答

1

當您設置hi = original_string您的hi變量只是一個指向同一對象的新變量。如果你看看hi.object_idoriginal_string.object_id,你會發現它們是一樣的。如果你想克隆一個對象,你可以在不影響 original_string的情況下操作,你需要說一些類似hi = original_string.clonehi = original_string.dup的東西。