Zip Multiple Arrays Together In Ruby
Combine elements from two or more arrays by position using Array#zip.
Description
Array#zip pairs elements from multiple arrays at the same index, returning an array of sub-arrays. It is the idiomatic way to combine parallel data structures — column headers with values, keys with computed results, or any set of co-indexed collections. Passing a block to zip iterates instead of building the intermediate array, which saves memory for large datasets.
Sample input:
names = ["Alice", "Bob", "Carol"]
scores = [95, 87, 92]
ranks = [1, 3, 2]
Sample Output:
[["Alice", 95, 1], ["Bob", 87, 3], ["Carol", 92, 2]]
Answer
names = ["Alice", "Bob", "Carol"]
scores = [95, 87, 92]
ranks = [1, 3, 2]
# Basic zip
combined = names.zip(scores, ranks)
# => [["Alice", 95, 1], ["Bob", 87, 3], ["Carol", 92, 2]]
# Convert to hashes
result = names.zip(scores).map { |name, score| { name: name, score: score } }
# => [{name: "Alice", score: 95}, {name: "Bob", score: 87}, {name: "Carol", score: 92}]
# Block form — no intermediate array
names.zip(scores) { |name, score| puts "#{name}: #{score}" }
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀