Created
January 12, 2010 05:44
-
-
Save seven1m/274945 to your computer and use it in GitHub Desktop.
A couple different ways of doing nested group_by. There are surely more...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
Person = Struct.new(:name, :age, :gender) | |
class GroupByTest < Test::Unit::TestCase | |
def setup | |
@people = [ | |
@jennie = Person.new('Jennie', 29, 'f'), | |
@justin = Person.new('Justin', 28, 'm'), | |
@manda = Person.new('Manda', 27, 'f'), | |
@jason = Person.new('Jason', 18, 'm'), | |
@tim = Person.new('Tim', 28, 'm'), | |
@kyler = Person.new('Kyler', 18, 'm'), | |
] | |
end | |
# first way | |
# just 2 lines of code | |
def test_nested_group_by | |
grouped = @people.group_by(&:gender) | |
grouped.each { |g, p| grouped[g] = p.group_by(&:age) } | |
assert_equal( | |
{ | |
'm' => { | |
28 => [@justin, @tim], | |
18 => [@jason, @kyler] | |
}, | |
'f' => { | |
27 => [@manda], | |
29 => [@jennie] | |
} | |
}, | |
grouped | |
) | |
end | |
# second way | |
# seems more readable to me, but more lines of code | |
def test_plain_loop | |
grouped = {} | |
@people.each do |person| | |
grouped[person.gender] ||= {} | |
grouped[person.gender][person.age] ||= [] | |
grouped[person.gender][person.age] << person | |
end | |
assert_equal( | |
{ | |
'm' => { | |
28 => [@justin, @tim], | |
18 => [@jason, @kyler] | |
}, | |
'f' => { | |
27 => [@manda], | |
29 => [@jennie] | |
} | |
}, | |
grouped | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment