concatenate two arrays in ruby

To concatenate two arrays in Ruby, you can use the + operator or the concat method.

Here's an example using the + operator:

main.rb
array1 = [1, 2, 3]
array2 = [4, 5, 6]
concatenated_array = array1 + array2
puts concatenated_array.inspect  # Output: [1, 2, 3, 4, 5, 6]
137 chars
5 lines

And here's an example using the concat method:

main.rb
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.concat(array2)
puts array1.inspect  # Output: [1, 2, 3, 4, 5, 6]
110 chars
5 lines

Both solutions will produce the same output - a new array that contains all elements from both arrays.

related categories

gistlibby LogSnag