我想要解释我在Koans中遇到的Ruby中的行为

前端之家收集整理的这篇文章主要介绍了我想要解释我在Koans中遇到的Ruby中的行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
那么只是修改原始字符串的铲子操作符吗?为什么这样做,它看起来像:
  1. hi = original_string

表现得像某种指针?我可以获得一些关于何时以及如何以及为何如此行为的见解?

  1. def test_the_shovel_operator_modifies_the_original_string
  2. original_string = "Hello,"
  3. hi = original_string
  4. there = "World"
  5. hi << there
  6. assert_equal "Hello,World",original_string
  7.  
  8. # THINK ABOUT IT:
  9. #
  10. # Ruby programmers tend to favor the shovel operator (<<) over the
  11. # plus equals operator (+=) when building up strings. Why?
  12. end

解决方法

在ruby中,一切都是参考.如果你做foo = bar,现在foo和bar是同一个对象的两个名字.

但是,如果你执行foo = foo bar(或等效地,foo = bar),foo现在引用一个新对象:一个是计算foo bar的结果.

猜你在找的Ruby相关文章