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:

  1. Using the push method:
  2. The push method adds one or more elements to the end of an array.
  3. Syntax: array.push(element1, element2, ...)
  4. Example: Let's say we have an array called numbers with the elements [1, 2, 3], and we want to add the number 4 to the end of the array. We can use the push method like this: numbers.push(4). After executing this code, the numbers array will be [1, 2, 3, 4].

  5. Using the shovel operator (<<):

  6. The shovel operator (<<) is a shorthand way to add an element to the end of an array.
  7. Syntax: array << element
  8. Example: Using the same numbers array as before, we can add the number 5 to the end of the array using the shovel operator like this: numbers << 5. After executing this code, the numbers 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.