Grouping by First Letter

Well, I needed to group by first letter today, so I read up on how to do it in Rails Recipes. Here’s what I ended up with:


>>  puts Student.find_all.group_by {|person| person.last_name[0]}.length
23
=> nil
>>  puts Faculty.find_all.group_by {|person| person.last_name[0]}.length
20

I’ll continue adding to this post as time goes on. I think I will have a sweet pagination solution soon.

Update:

Now, I have this, which actually does what I want:


@people = Person.find(:all, :order => 'last_name, first_name').group_by {|person| person.last_name[0].chr}.sort
@people[0][1].each {|fac| puts fac.last_name}

This outputs all the people with a last name starting with A. How Handy!



Comments are closed