Reputation: 75955
In PHP we can quickly concatenate strings:
$a = "b";
$a .= "c";
which returns "bc"
. How would we do this in Ruby?
Upvotes: 1
Views: 1279
Reputation: 96994
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.
Upvotes: 9
Reputation: 42949
irb(main):001:0> a = "ezcezc"
=> "ezcezc"
irb(main):002:0> a << "erer"
=> "ezcezcerer"
or
irb(main):003:0> a += "epruneiruv"
=> "ezcezcererepruneiruv"
Upvotes: 5