tags:

views:

246

answers:

4

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

+2  A: 
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.

sepp2k
A: 

Hashes aren't ordered.

JimNeath
That depends on your Ruby version.
James A. Rosen
+8  A: 
hash.keys.sort.each do |key|
  puts "#{key}-----"
  hash[key].each { |val| puts val }
end
erik
+1  A: 

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
glenn mcdonald
The hash keys are numbers, so '[k + "----"]' raises a TypeError (String can't be coerced into Fixnum). You need '[k.to_s + "----"]'
glenn jackman
True enough. I had letters in my test version. Fixed, using the even better "#{k}----".
glenn mcdonald