[LRUG] Sorting a hash by value
Tom Stuart
tom at codon.com
Tue Jun 17 04:14:09 PDT 2014
On 17 Jun 2014, at 11:46, Stephen Nelson-Smith <sanelson at gmail.com> wrote:
> I want to filter this hash by value and return them in sorted date order.
I'm not completely clear what you're after here, but here's what I'd do:
>> require 'time'
=> true
>> Server = Struct.new(:ami, :name, :time) do
def self.from_pair((ami, name_and_time))
name, time_string = name_and_time.split(' ')
new ami, name, Time.iso8601(time_string)
end
end
=> Server
>> servers = hash.map(&Server.method(:from_pair))
=> [
#<struct Server ami="ami-c3c73c7f", name="tn-example", time=1980-09-12 17:53:25 UTC>,
#<struct Server ami="ami-600925fe", name="sns-example", time=1983-01-05 16:21:08 UTC>,
#<struct Server ami="ami-131f1007", name="dk-example", time=2005-01-27 23:03:01 UTC>,
#<struct Server ami="ami-98d4ddef", name="tn-example", time=2002-10-27 11:52:26 UTC>,
#<struct Server ami="ami-fe6af742", name="sns-example", time=1998-11-22 09:54:51 UTC>,
#<struct Server ami="ami-09966e45", name="dk-example", time=1993-01-09 13:23:45 UTC>,
#<struct Server ami="ami-44e6ee6a", name="tn-example", time=2013-12-23 20:52:28 UTC>,
#<struct Server ami="ami-cbf7f1a9", name="sns-example", time=1979-09-09 07:15:47 UTC>,
#<struct Server ami="ami-fcd2e7ac", name="dk-example", time=2007-09-02 18:34:05 UTC>
]
>> servers.select { |server| server.name == 'sns-example' }.sort_by(&:time)
=> [
#<struct Server ami="ami-cbf7f1a9", name="sns-example", time=1979-09-09 07:15:47 UTC>,
#<struct Server ami="ami-600925fe", name="sns-example", time=1983-01-05 16:21:08 UTC>,
#<struct Server ami="ami-fe6af742", name="sns-example", time=1998-11-22 09:54:51 UTC>
]
Cheers,
-Tom
More information about the Chat
mailing list