Ruby Method of the Day - String.<<

Posted by Kelly McCauley on Aug 31, 2007

Signature

string << other_string      #=> string
string.concat(other_string) #=> string
string << integer           #=> string  # integer must be between 0 and 255
string.concat(integer)      #=> string  # integer must be between 0 and 255

string.<< appends other_string or the ascii character equivalent of integer and returns itself.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
x = 'foo'
x << 'bar'            #=> "foobar"
y = 'fred'
y.concat('bob')       #=> "fredbob"

# Since x.<< returns itself, multiple calls to << will append to the first
# string object.
x << 'baz' << 'foz'   #=> "foobarbazfoz"
y.concat('bill').concat('alice')    #=> "fredbobbillalice"

z = 'a'
z << 98 << 99         #=> "abc"
z.concat(100)         #=> "abcd"

begin
  a = ''
  a << 1000
rescue Exception => e
  e.inspect           #=> #<TypeError: can't convert Fixnum into String>
end

Documentation Reference

www.ruby-doc.org : String.<<, String.concat