sort 2d array or array of hashes in ruby on rails -
depending on makes easier sort can either have array of arrays or array of hashes. e.g.
i have id
s , other fields like
dateviews` etc. can either in format
[[1,"2014-01-01",50],[2,"2014-02-05",20],...]
or [{:id=>1, :date=> "2014-01-01", :views=>50},{:id=>2,:date=>"2014-02-05",:views=>20}]
now need able sort or access mins/maxs quickly. instance in view want call .max.views
, .min.views
or smth compare entry highest views , 1 lowest views.
the ruby sort_by
method confusing , don't see how can access minimum date or latest 3 dates, etc..
very simple. need method enumerable#minmax_by
:
hash = [ {:id=>1, :date=> "2014-01-01", :views=>50}, {:id=>2,:date=>"2014-02-05",:views=>20} ] min,max = hash.minmax_by { |h| h[:views] }
how can access minimum date or latest 3 dates, etc..
require 'date' # latest 3 dates hash.sort_by { |h| date.strptime(h[:date],"%y-%m-%d") }.last(3) # minimum date hash.sort_by { |h| date.strptime(h[:date],"%y-%m-%d") }.first
Comments
Post a Comment