To iterate over a map of maps in Ruby, you can use nested loops. The outer loop iterates over the outer hash, and the inner loop iterates over the inner hash.
We can iterate over a map of maps in Ruby where both the outer and inner hashes use integers for keys and values. This example demonstrates using nested loops to print each key-value pair.
For example,
outer_hash
.outer_hash = {
1 => {1 => 10, 2 => 20, 3 => 30},
2 => {4 => 40, 5 => 50, 6 => 60}
}
# Iterate over the hash of hashes
puts 'Iterating over hash of hashes with integer keys and values:'
outer_hash.each do |outer_key, inner_hash|
puts "Outer key: #{outer_key}"
inner_hash.each do |inner_key, value|
puts " Inner key: #{inner_key}, value: #{value}"
end
end
Iterating over hash of hashes with integer keys and values: Outer key: 1 Inner key: 1, value: 10 Inner key: 2, value: 20 Inner key: 3, value: 30 Outer key: 2 Inner key: 4, value: 40 Inner key: 5, value: 50 Inner key: 6, value: 60
We can iterate over a map of maps in Ruby where the outer hash uses strings for keys and the inner hashes use integers for keys and strings for values. This example demonstrates using nested loops to print each key-value pair.
For example,
outer_hash
with mixed key and value types.outer_hash = {
'first' => {1 => 'one', 2 => 'two', 3 => 'three'},
'second' => {4 => 'four', 5 => 'five', 6 => 'six'}
}
# Iterate over the hash of hashes
puts 'Iterating over hash of hashes with mixed key and value types:'
outer_hash.each do |outer_key, inner_hash|
puts "Outer key: #{outer_key}"
inner_hash.each do |inner_key, value|
puts " Inner key: #{inner_key}, value: #{value}"
end
end
Iterating over hash of hashes with mixed key and value types: Outer key: first Inner key: 1, value: one Inner key: 2, value: two Inner key: 3, value: three Outer key: second Inner key: 4, value: four Inner key: 5, value: five Inner key: 6, value: six
We can iterate over a map of maps in Ruby where both the outer and inner hashes use strings for keys and floats for values. This example demonstrates using nested loops to print each key-value pair.
For example,
outer_hash
with strings for keys and floats for values.outer_hash = {
'group1' => {'A' => 1.1, 'B' => 2.2, 'C' => 3.3},
'group2' => {'D' => 4.4, 'E' => 5.5, 'F' => 6.6}
}
# Iterate over the hash of hashes
puts 'Iterating over hash of hashes with string keys and float values:'
outer_hash.each do |outer_key, inner_hash|
puts "Outer key: #{outer_key}"
inner_hash.each do |inner_key, value|
puts " Inner key: #{inner_key}, value: #{value}"
end
end
Iterating over hash of hashes with string keys and float values: Outer key: group1 Inner key: A, value: 1.1 Inner key: B, value: 2.2 Inner key: C, value: 3.3 Outer key: group2 Inner key: D, value: 4.4 Inner key: E, value: 5.5 Inner key: F, value: 6.6
In this tutorial, we learned How to Iterate Over a Map of Maps in Ruby language with well detailed examples.