简体   繁体   中英

sort 2d array or array of hashes in ruby on rails

Depending on what makes it easier to sort by I can either have an array of arrays or an array of hashes. Eg

I have id s and other fields like date views` etc. I can either get it in this 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 I need to be able to sort this or access the mins/maxs quickly. For instance in my view I want to call .max.views and .min.views or smth to compare the entry with the highest views and the one with the lowest views.

The ruby sort_by method is really confusing and I don't see how I can access say the minimum date or the latest 3 dates, etc..

Very simple. You need to look into the 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 I can access say the minimum date or the latest 3 dates, etc..

require 'date'

# the 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

Min Max can be accessed by @ArupRakshit's method and to get things "like minimum date or the latest 3 dates" you can use the sort_by method

hash = [
     {:id=>1, :date=> "2014-01-01", :views=>50},
     {:id=>2,:date=>"2014-02-05",:views=>20}
     {:id=>3,:date=>"2014-02-10",:views=>100}
     {id:=>4, :date=>"2014-03-02",:views=>12}
   ]
hash.sort_by{|h| h[:views]}
#=>[{:id=>4, :date=>"2014-03-02", :views=>12}, {:id=>2, :date=>"2014-02-05", :views=>20}, {:id=>1, :date=>"2014-01-01", :views=>50}, {:id=>3, :date=>"2014-02-10", :views=>100}]

Minimum Date:

hash.sort_by{|h| h[:date]}.first
#=> {:id=>1, :date=> "2014-01-01", :views=>50}

Latest 3 Dates:

hash.sort_by{|h| h[:date]}.slice(-3..-1)
#=>[{:id=>2, :date=>"2014-02-05", :views=>20}, {:id=>3, :date=>"2014-02-10", :views=>100}, {:id=>4, :date=>"2014-03-02", :views=>12}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM