add an element to the beginning of an array in ruby

The unshift method can be used to add an element to the beginning of an array in Ruby. Here's an example:

main.rb
arr = [2, 3, 4]
arr.unshift(1)
puts arr #=> [1, 2, 3, 4]
57 chars
4 lines

In this example, the unshift method is used to add the integer 1 to the beginning of the arr array. The resulting array is [1, 2, 3, 4].

Note that the unshift method mutates the original array. If you want to add an element to the beginning of an array without modifying the original array, you can create a new array and concatenate the element to the beginning like this:

main.rb
arr = [2, 3, 4]
new_arr = [1] + arr
puts new_arr #=> [1, 2, 3, 4]
66 chars
4 lines

related categories

gistlibby LogSnag