I have a hash like this:
{
1=>["a", "b"],
2=>["c"],
3=>["a", "d", "f", "g"],
4=>["q"]
}
How can I iterate it in order to get:
1-----
a
b
2-----
c
3-----
a
d
f
g
I have a hash like this:
{
1=>["a", "b"],
2=>["c"],
3=>["a", "d", "f", "g"],
4=>["q"]
}
How can I iterate it in order to get:
1-----
a
b
2-----
c
3-----
a
d
f
g
hash.each do |key, array|
puts "#{key}-----"
puts array
end
Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.
hash.keys.sort.each do |key|
puts "#{key}-----"
hash[key].each { |val| puts val }
end
Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:
puts h.sort.map {|k,v| ["#{k}----"] + v}
And if you don't actually need the "----" part, it can be just:
puts h.sort