I want to get a specific output iterating a Ruby Hash.
This is the Hash I want to iterate over:
hash = {
1 => ['a', 'b'],
2 => ['c'],
3 => ['d', 'e', 'f', 'g'],
4 => ['h']
}
This is the output I would like to get:
1-----
a
b
2-----
c
3-----
d
e
f
g
4-----
h
In Ruby, how can I get such an output with my Hash ?
The most basic way to iterate over a hash is as follows:
You can also refine
Hash::each
so it will support recursive enumeration. Here is my version ofHash::each
(Hash::each_pair
) with block and enumerator support:Here are usage examples of
Hash::each
with and withoutrecursive
flag:Here is example from the question itself:
Also take a look at my recursive version of
Hash::merge
(Hash::merge!
) here.Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:
And if you don't actually need the "----" part, it can be just:
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
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.