# Sub Hashes

**URL:** <https://www.ruby-forum.com/t/sub-hashes/67672>\
**Category:** Ruby\
**Created:** [December 15, 2005, 9:53pm UTC](https://www.ruby-forum.com/t/sub-hashes/67672 "2005-12-15T21:53:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![cowboy\_x](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/d78d45/32.png) [@cowboy\_x](https://www.ruby-forum.com/u/cowboy_x)\
**Post date:** [December 15, 2005, 9:53pm UTC](https://www.ruby-forum.com/t/sub-hashes/67672/1 "2005-12-15T21:53:40Z")

</div>

Hi,

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:

%irb

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

Another solution, even more terse could be:

> > a.sort.select{|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.
