代码之家  ›  专栏  ›  技术社区  ›  Mongus Pong

<<与+有何不同?

  •  15
  • Mongus Pong  · 技术社区  · 15 年前

    我在Ruby中看到了很多这样的事情:

    myString = "Hello " << "there!"
    

    这和做什么不同?

    myString = "Hello " + "there!"
    
    1 回复  |  直到 15 年前
        1
  •  25
  •   Crast    15 年前

    在Ruby中,字符串是可变的。也就是说,字符串值实际上可以更改,而不仅仅是替换为另一个对象。 x << y 实际上会将字符串y添加到x,而 x + y 将创建一个新字符串并返回该字符串。

    这可以在Ruby解释器中简单地测试:

    irb(main):001:0> x = "hello"
    => "hello"
    irb(main):002:0> x << "there"
    => "hellothere"
    irb(main):003:0> x
    => "hellothere"
    irb(main):004:0> x + "there"
    => "hellotherethere"
    irb(main):005:0> x
    => "hellothere"
    

    值得注意的是,请看 x + "there" 返回“hellotherethere”,但 x 没有改变。小心可变的线,它们会来咬你。大多数其他托管语言没有可变字符串。

    还要注意,字符串上的许多方法都有破坏性和非破坏性版本: x.upcase 将返回一个包含X的大写版本的新字符串,而不返回X; x.upcase! 将返回大写值-并-修改X指向的对象。