You can push elements in an array to the end of the array with the push()
method or <<
operator. In this shot, we will learn how to use the <<
operator to add elements to an array.
The <<
operator pushes elements to the end of the array. This can be chained together, meaning that several elements can be added to the end of an array at the same time with the <<
operator.
array << obj
obj
: The element to be appended to the array; obj
can be a single element or an array.
The <<
operator returns the array itself with the appended elements.
In the code below, we demonstrate the use of the <<
operator. We append several elements to an array and display the returned values on the console.
# create Ruby arraysarray1 = [1, 2, 3, 4]array2 = [["ab", "cd"], ["ef", "gh"]]array3 = ["For", "While", "Do While"]array4 = ["Google", "Netflix", "Amazon"]# append elements to the# arrays using the "<<" operatora = array1 << 5b = array2 << ["ij", "kl"]c = array3 << "Switch Statement"d = array4 << "Apple" << "Meta"# display returned values to the consoleputs "#{a}" # 5 is appendedputs "#{b}" # ["ij", "kl"] is appendedputs "#{c}" # "Switch Statement" is appendedputs "#{d}" # "Apple" and "Meta" are appended
In the code above, we see that several elements are appended to the arrays we created with the <<
operator.