Chaining Array Appends With <<

There are a couple of ways to add an element to an array in Ruby. The easiest is the << operator. It works like so:


a = []
a << "One"
a << "Two"
a # puts ["One", "Two"]

The interesting thing is that this method returns the array, which allows you to chain elements; you can write the above code like so:


a = []
a << "One" << "Two" << "Three"
a #puts ["One", "Two", "Three"]

Nice! Just makes life a little easier.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.