How to get a specific output iterating a hash in Ruby?

sts picture sts · Aug 4, 2009 · Viewed 287.8k times · Source

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 ?

Answer

sepp2k picture sepp2k · Aug 4, 2009
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.