how to add to array ruby
To add an element to an array in Ruby, you can use the push
method or the shovel operator (<<
). Here's how you can do it:
- Using the
push
method: - The
push
method adds one or more elements to the end of an array. - Syntax:
array.push(element1, element2, ...)
Example: Let's say we have an array called
numbers
with the elements[1, 2, 3]
, and we want to add the number4
to the end of the array. We can use thepush
method like this:numbers.push(4)
. After executing this code, thenumbers
array will be[1, 2, 3, 4]
.Using the shovel operator (
<<
):- The shovel operator (
<<
) is a shorthand way to add an element to the end of an array. - Syntax:
array << element
- Example: Using the same
numbers
array as before, we can add the number5
to the end of the array using the shovel operator like this:numbers << 5
. After executing this code, thenumbers
array will be[1, 2, 3, 4, 5]
.
These methods modify the original array by adding the new element(s) to the end. If you want to create a new array without modifying the original one, you can use the +
operator to concatenate arrays. For example: new_array = array + [element]
.
I hope this helps! Let me know if you have any further questions.