那么只是修改原始字符串的铲子操作符吗?为什么这样做,它看起来像:
- hi = original_string
表现得像某种指针?我可以获得一些关于何时以及如何以及为何如此行为的见解?
- 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
解决方法
在ruby中,一切都是参考.如果你做foo = bar,现在foo和bar是同一个对象的两个名字.
但是,如果你执行foo = foo bar(或等效地,foo = bar),foo现在引用一个新对象:一个是计算foo bar的结果.