From: Martin DeMello Date: 2005-06-13T13:20:31+09:00 Subject: Re: finding Hash subsets based on key value ee wrote: > Hi > > Is there a simple way of searching the keys of a Hash to find a subset. > I have a set of keys with two values indicating group and sub-group, > eg: > > group_1_item_1 > group_2_item_2 > group_1_item_2 > group_1_item_4 > group_2_item_3 > > I'd like to divide them into groups, but without having to loop through > the entire collection and having to test each key You can't get away without testing each key under the hood (this is intrinsically an O(n) problem), but this should make it syntactically convenient at least: hash.partition {|k,v| k =~ /group_1/ }.map {|i| Hash[*i.flatten]} Enumerable#partition divides your collection into two parts, based on whether the block returns true or false, so it doesn't scale to more than two subsets, but for your example it should work nicely. martin