Question
How to Add One Array to Another in Ruby Without Creating a Nested Array
Question
I want to add the contents of one array to another in Ruby without ending up with a multi-dimensional array.
I tried this:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
I expected this result:
["some", "thing", "another", "thing"]
But instead I got:
["some", "thing", nil]
Why does this happen, and what is the correct way to combine arrays in Ruby so the elements are added individually rather than as a nested array?
Short Answer
By the end of this page, you will understand why push and flatten! produced nil, how Ruby array methods behave when combining arrays, and when to use concat, +, push, or the splat operator to get the result you want.
Concept
In Ruby, there is an important difference between:
- adding an array as one element
- adding the elements of an array into another array
That difference is the reason beginners often get nested arrays or unexpected nil values.
The key idea
If you do this:
somearray.push(anotherarray)
Ruby treats anotherarray as a single object and adds it as one item:
["some", "thing", ["another", "thing"]]
That creates a nested array.
If you want to add each element individually, use a method designed for that, such as:
somearray.concat(anotherarray)
Result:
["some", "thing", "another", "thing"]
Why flatten! returned nil
The method flatten! modifies an array in place . If the array is already flat, Ruby returns .
Mental Model
Think of an array like a shopping bag.
push(item)puts one item into the bag.- If that item is another bag, you now have a bag inside a bag.
concat(other_bag_contents)empties the contents of the second bag into the first bag.flattenis like opening smaller bags inside the bag and spreading their contents out.
Now imagine flatten! saying:
- "I only report back with the bag if I had to rearrange something."
- "If everything was already flat, I return
nil."
So when you used push(anotherarray.flatten!), Ruby basically did this:
- looked at the second bag
- saw it was already flat
- returned
nil - pushed
nilinto the first bag
That is why you got nil instead of the array elements.
Syntax and Examples
Common ways to combine arrays in Ruby
1. Use concat to add elements into the same array
a = ["some", "thing"]
b = ["another", "thing"]
a.concat(b)
p a
# ["some", "thing", "another", "thing"]
concat modifies a.
2. Use + to create a new combined array
a = ["some", "thing"]
b = ["another", "thing"]
c = a + b
p c
# ["some", "thing", "another", "thing"]
This does not modify a or b.
3. Use push to add one item
a = ["some", "thing"]
b = ["another", "thing"]
a.push(b)
p a
Step by Step Execution
Consider this code:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
Step 1: Create somearray
somearray = ["some", "thing"]
Current value:
["some", "thing"]
Step 2: Create anotherarray
anotherarray = ["another", "thing"]
Current value:
["another", "thing"]
Step 3: Evaluate anotherarray.flatten!
anotherarray.flatten!
Ruby checks whether anotherarray contains nested arrays.
Real World Use Cases
Arrays are combined constantly in Ruby applications.
Building a list of tags
default_tags = ["ruby", "backend"]
user_tags = ["api", "json"]
all_tags = default_tags + user_tags
Combining validation errors
errors = []
errors.concat(name_errors)
errors.concat(email_errors)
Merging search results
results = []
results.concat(products)
results.concat(categories)
Collecting CLI arguments
base_args = ["--verbose"]
extra_args = ["--output", "report.txt"]
args = base_args + extra_args
Processing API data
all_records = []
all_records.concat(page_1_records)
all_records.concat(page_2_records)
In each case, you need to decide whether:
- you want to mutate the original array with
concat - or create a new array with
+
Real Codebase Usage
In real projects, developers choose array-combining methods based on intent.
Use concat when mutation is intentional
items = []
items.concat(load_defaults)
items.concat(load_user_items)
This is common when building up one array over time.
Use + when you want immutability
final_roles = default_roles + extra_roles
This is clearer when you want to keep the original arrays unchanged.
Use guard clauses before combining
return [] if records.nil?
Or:
items.concat(new_items) if new_items
This helps avoid errors when values may be nil.
Use splat for method arguments
params = ["name", "email"]
log_fields(*params)
The splat operator is useful when a method expects separate values rather than an array.
Common pattern: collect then flatten later
Common Mistakes
1. Using push when you mean concat
Broken code:
a = [1, 2]
b = [3, 4]
a.push(b)
p a
# [1, 2, [3, 4]]
Why it happens:
pushaddsbas one element
Fix:
a.concat(b)
# [1, 2, 3, 4]
2. Expecting flatten! to always return an array
Broken code:
a = [1, 2]
p a.flatten!
# nil
Why it happens:
flatten!returnsnilwhen nothing changes
Fix:
p a.flatten
# [1, 2]
Comparisons
| Method | What it does | Modifies original? | Nested array risk? | Typical use |
|---|---|---|---|---|
push(obj) | Adds one object to the end | Yes | Yes | Add a single item |
<< obj | Same basic idea as push for one item | Yes | Yes | Short form for adding one item |
concat(array) | Adds each element of another array | Yes | No | Merge into existing array |
a + b | Returns a new combined array | No |
Cheat Sheet
Quick reference
Add one item
array.push(item)
array << item
Add all elements from another array
array.concat(other_array)
Create a new combined array
new_array = array1 + array2
Expand array into separate arguments
array.push(*other_array)
Flatten nested arrays
flat = array.flatten # new array
array.flatten! # modifies original, may return nil
Important rules
pushadds one objectconcatadds elements from another array+returns a new arrayflatten!returnsnilif no changes were made<<can create nested arrays if you append an array
FAQ
How do I append one array to another in Ruby without nesting?
Use concat or +:
a.concat(b)
# or
c = a + b
Why does flatten! return nil in Ruby?
flatten! returns nil when the array was already flat and Ruby did not need to change anything.
What is the difference between push and concat in Ruby?
push adds one object as a single element. concat adds each element from another array.
Does + modify the original array in Ruby?
No. + creates and returns a new array.
Is << the same as concat?
No. << adds one item. If that item is an array, you get a nested array.
Mini Project
Description
Build a small Ruby script that combines task lists from two sources: a default list and a user-provided list. This project demonstrates the difference between adding one array as a single item and merging array elements correctly.
Goal
Create a Ruby program that merges two task arrays into one flat list without nesting.
Requirements
- Create one array of default tasks.
- Create one array of extra tasks.
- Combine them into a single flat array.
- Print the final merged task list.
- Show at least one incorrect approach and then the correct one.
Keep learning
Related questions
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Difference Between require and include in Ruby
Learn the difference between require and include in Ruby, when to load a file, and when to mix module methods into a class.
Fixing Ruby Gem Native Extension Errors: mkmf.rb Can't Find Header Files for Ruby
Learn why Ruby gem installs fail with missing ruby.h, how native extensions work, and how to fix header file errors on Linux servers.