From: Stefano Crocco Date: 2009-02-13T23:26:59+09:00 Subject: Re: Meaning of "<<"? Alle Friday 13 February 2009, Chris Davies ha scritto: > Hi, > > I'm currently trying to learn ruby, coming from a perl/unix > background. I've been working through one of the many online tutorials > and it's suddenly thrown in the "<<" operator. > > Now, I'm familiar with a the use of "<<" as a bitwise left shift > and as a here doc, but this one throws me. The relevant URL is > http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html > and here's a variation on the theme for illustrative purposes: > > str = 'one' > str << 'two' > puts str # onetwo > > It seems to me that << in this context is equivalent to +=, but I can't > find any documentation explaining /why/ this is the case, and why I > should use one in preference to the other. (Google really doesn't like > "<<".) > > Any suggestions, please? > Cheers, > Chris This is the documentation for the String << operator (that is, for the String#<< method): str << fixnum => str str.concat(fixnum) => str str << obj => str str.concat(obj) => str From Ruby 1.8 ------------------------------------------------------------------------ Append---Concatenates the given object to _str_. If the object is a +Fixnum+ between 0 and 255, it is converted to a character before concatenation. a = "hello " a << "world" #=> "hello world" a.concat(33) #=> "hello world!" The difference between << and + is that << modifies the first string, while + creates a new string, made of the caracters of the first string followed by the characters of the second. Too see the difference, look at this example: a = "first string" b = "second string" puts "Using +" a + b puts a puts b puts "Using <<" a << b puts a puts b The output is: Using + first string second string Using << first stringsecond string second string As you can see, in the second case, a has been modified, while in the first case it wasn't. In general, to obtain documentation about ruby classes and methods, you can use the ri command: ri 'String#<<' which will give the documentation I posted above. There's also an online API reference at http://www.ruby-doc.org/core/ I hope this helps Stefano