add an element to the end of an array in ruby

To add an element to the end of an array in Ruby, you can use the push method. This will append the specified element to the end of the array.

main.rb
arr = [1, 2, 3]
arr.push(4)
#=> [1, 2, 3, 4]
45 chars
4 lines

Alternatively, you can use the << operator, which also appends an element to the end of an array.

main.rb
arr = [1, 2, 3]
arr << 4
#=> [1, 2, 3, 4]
42 chars
4 lines

related categories

gistlibby LogSnag