问题
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:
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"
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