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
主要是在講用了hi = original_string 之後改變hi裡面的值會連original_string的值也一起改了 Ruby裡面這些都是reference,hi = original_string 之後他們兩個就會參照到同一個物件
2.3.1 :121 > original_string.object_id
=> 70169322460680
2.3.1 :122 > hi.object_id
=> 70169322460680
如果今天是用+=的話,因為這是一個assignment,他們的object_id就會不一樣了2.3.1 :112 > original_string = "Hello, "
=> "Hello, "
2.3.1 :113 > hi = original_string
=> "Hello, "
2.3.1 :114 > there = "World"
=> "World"
2.3.1 :115 > hi += there
=> "Hello, World"
2.3.1 :116 > hi
=> "Hello, World"
2.3.1 :117 > original_string
=> "Hello, "
Written with StackEdit.
沒有留言:
張貼留言