Forum: Ruby Sub Hashes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C5eecd44fa818c7985d4f31bc2c42ac9?d=identicon&s=25 Eric Jacoboni (Guest)
on 2005-12-15 21:53
(Received via mailing list)
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.
This topic is locked and can not be replied to.