[LRUG] Sorting a hash by value
carlos
djmutiny at gmail.com
Tue Jun 17 03:59:56 PDT 2014
A quick go at this:
catalogue.select{|k,v| v =~ /sns/}.sort_by{|k,v|
Date.parse(v.gsub(/.w{2}\-example /, ''))}
2014-06-17 11:46 GMT+01:00 Stephen Nelson-Smith <sanelson at gmail.com>:
> I have a hash that looks like this:
>
> {"ami-c3c73c7f"=>"tn-example 1980-09-12T17:53:25Z",
> "ami-600925fe"=>"sns-example 1983-01-05T16:21:08Z",
> "ami-131f1007"=>"dk-example 2005-01-27T23:03:01Z",
> "ami-98d4ddef"=>"tn-example 2002-10-27T11:52:26Z",
> "ami-fe6af742"=>"sns-example 1998-11-22T09:54:51Z",
> "ami-09966e45"=>"dk-example 1993-01-09T13:23:45Z",
> "ami-44e6ee6a"=>"tn-example 2013-12-23T20:52:28Z",
> "ami-cbf7f1a9"=>"sns-example 1979-09-09T07:15:47Z",
> "ami-fcd2e7ac"=>"dk-example 2007-09-02T18:34:05Z"}
>
> I want to filter this hash by value and return them in sorted date order.
> The implementation I have just seems ugly:
>
> catalogue.select {|id, name| name.match /sns-example/ }.sort { |id, name|
> name[1] <=> id[1] }
> => [["ami-a65e21cc", "sns-example 2011-10-03T11:15:49Z"],
> ["ami-9a401c41", "sns-example 1983-09-22T15:26:00Z"],
> ["ami-9f9ae4d8", "sns-example 1971-03-06T03:58:52Z"]]
>
>
> I don't like the way sort takes my hash and makes it into an array of
> tuples... and I'd really like it to return an array of single key/value
> hashes...
>
> Also, is there a more elegant way to perform the filter/search?
>
> S.
>
> --
> Stephen Nelson-Smith
> Technical Director
> Atalanta Systems Ltd
> www.atalanta-systems.com
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20140617/55963f56/attachment-0003.html>
More information about the Chat
mailing list