In Ruby, prepend
and append
are methods used to add elements to the beginning and end of arrays, respectively.
-
prepend:
- The
prepend
method is used to add one or more elements to the beginning of an array. - Syntax:
array.prepend(element)
or
array.prepend(element1, element2, ...)
- Example:
numbers = [3, 4, 5] numbers.prepend(2) # => [2, 3, 4, 5]
or
numbers = [4, 5] numbers.prepend(2, 3) # => [2, 3, 4, 5]
- The
-
append:
- The
append
method is an alias for the<<
operator and is used to add one or more elements to the end of an array. - Syntax:
array.append(element)
or
array << element
or
array.concat(other_array)
- Example:
numbers = [1, 2, 3] numbers.append(4) # => [1, 2, 3, 4]
or
numbers = [1, 2, 3] numbers << 4 # => [1, 2, 3, 4]
or
numbers = [1, 2, 3] numbers.concat([4, 5]) # => [1, 2, 3, 4, 5]
- The
In summary, prepend
adds elements to the beginning of an array, while append
(or <<
or concat
) adds elements to the end of an array. These methods are commonly used for array manipulation in Ruby.