Appending or pushing arrays, elements, or objects to an array is easy. This can be done using the <<
operator, which pushes elements or objects to the end of the array you want to append to. The magic of using <<
is that it can be chained.
array << object
object
: This could be an element or an array. You can append as many as you want.
A new array is returned, which is the original array and the appended elements.
In the example below, we create arrays and append some elements or arrays to them. We also chain appends and print the returned values to the console.
# creare arrayslanguagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]numbersArray = [1, 2, 3, 4, 5]alphabetsArray = ["a", "b", "c", "d", "e"]booleanArray = [true, false]animalsArray = ["dog", "cat", "rat", "cow", "bat"]# append elements to these arraysa = languagesArray << "C" # One appendb = numbersArray << 6 << 7 << 8 # Chianed elementsc = alphabetsArray << "f" << "g" << ["a", "e", "i", "o", "u"]d = booleanArray << false << truee = animalsArray << ["lion", "tiger", "wolf"] << "goat"# print values to the consoleputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"puts "#{e}"
In the code above, we created several arrays and appended some items to then. In line 9, only one element was appended to the languagesArray
. From line 10 to line 13, we then chained the appends.