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 ids , other fields likedateviews` 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

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -