Ruby equivalent of PHP's “.=” (dot equals) operator

两盒软妹~` 提交于 2019-12-29 08:20:56

问题


In PHP we can quickly concatenate strings:

$a = "b";
$a .= "c";

which returns "bc". How would we do this in Ruby?


回答1:


irb(main):001:0> a = "ezcezc"
=> "ezcezc"
irb(main):002:0> a << "erer"
=> "ezcezcerer"

or

irb(main):003:0> a += "epruneiruv"
=> "ezcezcererepruneiruv"



回答2:


There are essentially two different ways:

  1. Concatenation in place with << (known as the "shovel"), this is equivalent to calling concat. Note that, like most operators in Ruby, << is a method call.

    str = "foo"
    str << "bar"
    str  #=> "foobar"
    
  2. Concatenate and assign with +=:

    str = "foo"
    str += "bar"
    str  #=> "foobar"
    

    It's important to note that this is the same as:

    str = "foo"
    str = (str + "bar")
    

    which means that with this way a new object is created, while with the first way one is not, as the object is modified in place.




回答3:


Try this out:

string += another_string



回答4:


You can do string << another_string as well



来源:https://stackoverflow.com/questions/9706903/ruby-equivalent-of-phps-dot-equals-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!