From: "Matthew K. Williams" Date: 2010-04-08T02:04:16+09:00 Subject: Re: Manipulating of an Array of Structs On Thu, 8 Apr 2010, Anthony Wright wrote: > I have data that I've extracted from a database, that I wish to pass to > a calling (external) piece of software through Drb. > > The are a large number of data set formats, but an employee based > example might look something like: > > ID Name Age > 1 Mary Smith 23 > 3 Frank Zappa 52 > 19 Mary Jones 41 > > I'm trying to find a "nice" structure to pass this data around in, so > that it can be easily understood and manipulated. > > > > > I'm currently using an Array of Hashes so it looks something like: > > [ { :id => 1, :name => "Mary Smith", :age => 23 }, { :id => 3, :name => > "Frank Zappa", :age => 52 }, { :id =>19, :name => "Mary Jones", :age => > 41 } ] > > or more nicely formatted > > [ > { :id => 1, :name => "Mary Smith", :age => 23 }, > { :id => 3, :name => "Frank Zappa", :age => 52 }, > { :id =>19, :name => "Mary Jones", :age => 41 } > ] > > > > This is fine if I want to extract single pieces of information, but it's > clumsy to manipulate the whole array, for example, extract out all the > names, sort the array by age, create a new array containing employees > over 40. It's also inefficient as I'm repeating the labels on every record. > > I realise I can do this by writing block code to process the array, but > I feel there must be a cleaner way to store and manipulate data of this > form in ruby. Something on the lines of Struct would be great to remove > the excessing labels, but Struct doesn't help with the array manipulation. > Take a gander at Dr Nic's map_by_method gem, it has this functionality -- including sort_by, group_by, and index_by http://drnicwilliams.com/category/ruby/map_by_method/