im from php,
in php i overly use .=
so, how do it in ruby?
Asked
Active
Viewed 254 times
2
-
1There is no `=.` operator in PHP, only `.=`. – Gumbo Apr 05 '11 at 07:03
-
I'm sure there is lots of ways to produce the equivalent of PHP's "Parse error: syntax error" you'd get for using `=.`. – Gordon Apr 05 '11 at 07:24
-
possible duplicate of [String concatenation and Ruby](http://stackoverflow.com/questions/377768/string-concatenation-and-ruby) – Hans Olsson Apr 05 '11 at 14:18
3 Answers
6
String concatentation is done with +
in Ruby:
$ irb
irb(main):001:0> "hello" + " " + "world"
=> "hello world"
irb(main):002:0> foo = "hello "
=> "hello "
irb(main):003:0> foo += "world"
=> "hello world"
@AboutRuby also mentions the <<
operator:
irb(main):001:0> s = "hello"
=> "hello"
irb(main):002:0> s << " world"
=> "hello world"
irb(main):003:0> s
=> "hello world"
While his point that +
creates a new string and <<
modifies a string might seem like a small point, it matters a lot when you might have multiple references to your string object, or if your strings grow to be huge via repeated appending:
irb(main):004:0> my_list = [s, s]
=> ["hello world", "hello world"]
irb(main):005:0> s << "; goodbye, world"
=> "hello world; goodbye, world"
irb(main):006:0> my_list
=> ["hello world; goodbye, world", "hello world; goodbye, world"]
irb(main):007:0> t = "hello, world"
=> "hello, world"
irb(main):008:0> my_list = [t, t]
=> ["hello, world", "hello, world"]
irb(main):009:0> t += "; goodbye, world"
=> "hello, world; goodbye, world"
irb(main):010:0> my_list
=> ["hello, world", "hello, world"]
@AboutRuby mentioned he could think of three mechanisms for string concatenation; that reminded me of another mechanism, which is more appropriate when you've got an array of strings that you wish to join together:
irb(main):015:0> books = ["war and peace", "crime and punishment", "brothers karamozov"]
=> ["war and peace", "crime and punishment", "brothers karamozov"]
irb(main):016:0> books.join("; ")
=> "war and peace; crime and punishment; brothers karamozov"
The .join()
method can save you from writing some awful loops. :)

sarnold
- 102,305
- 22
- 181
- 238
-
The `<<` operator is usually preferred to `+=`. The `+=` creates another String object, `<<` appends to the string without creating another object. – AboutRuby Apr 05 '11 at 08:28
-
@AboutRuby, good point; examples added. I suggest adding an answer here too, so it can be upvoted. :) – sarnold Apr 05 '11 at 08:40
1
Is that for string concatenation? You use +=
in ruby to concat string.

Joshua Partogi
- 16,167
- 14
- 53
- 75