Sub Hashes



Say i have a hash representing a book index (keys are strings,
values are lists of pages, to keep things simple…).

When i want to print this index, i need to produce theses hash entries
sorted on the keys and grouped by the first letter of these keys.

I have found a “solution”, but i wonder if there is something
simpler… My approach is to produce an array of keys beginning with a
given letter (A, then B, then C, etc.), sort this array, then, for each
item in this sorted array, access the initial hash to get the
corresponding value…

I’m not sure i’m very clear… Hence an exemple. Say i want to
produce all values for keys beginning with b or B:


a = {“Bla” => 1, “Truc” => 2, “Bli” => 3, “Foo” => 3, “Bar” => 3}
result = []{|k,v| k.capitalize[0,1] == “B”}.each{|x| result << x.first}
=> [“Bla”, “Bar”, “Bli”]

result.sort.each{|k| puts “#{k} : #{a[k]}”}
Bar : 3
Bla : 1
Bli : 3

Another solution, even more terse could be:{|k| k.first.capitalize[0,1] == “B”}.each{|x| puts “#{x.first} #{a[x.first]}”}

In fact, i “only” want to produce a sub-hash given some key pattern
but i’ve no found how to do it directly with Ruby hashes, but my
solutions seems too tricky to be honnest.