Tarang
Tarang

Reputation: 75955

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

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

Answers (4)

Andrew Marshall
Andrew Marshall

Reputation: 96994

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.

Upvotes: 9

TheDude
TheDude

Reputation: 3952

You can do string << another_string as well

Upvotes: 1

SirDarius
SirDarius

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

MrDanA
MrDanA

Reputation: 11647

Try this out:

string += another_string

Upvotes: 3

Related Questions