2013-06-28 189 views
0

我想按照受歡迎程度值對數組進行排序。我怎樣才能做到這一點?按照下一級值對數組頂級進行排序 - Ruby

[ 
    { 
    "id"=>1, 
    "popularity"=>7.77030797174916, 
    "title"=>"Another film", 
    }, 
    { 
    "id"=>2, 
    "popularity"=>2.7703074916, 
    "title"=>"A film", 
    }, 
    { 
    "id"=>3, 
    "popularity"=>9.77030797174916, 
    "title"=>"A third film", 
    } 
] 
+0

使用'sort_by',然後寫一個翻出普及塊 –

回答

0

顯然我們應該在這裏使用Enumerable#sort_by

a = [ 
    { 
    "id"=>1, 
    "popularity"=>7.77030797174916, 
    "title"=>"Another film", 
    }, 
    { 
    "id"=>2, 
    "popularity"=>2.7703074916, 
    "title"=>"A film", 
    }, 
    { 
    "id"=>3, 
    "popularity"=>9.77030797174916, 
    "title"=>"A third film", 
    } 
] 
a.sort_by{|h| h["popularity"]} 
# => [{"id"=>2, "popularity"=>2.7703074916, "title"=>"A film"}, 
#  {"id"=>1, "popularity"=>7.77030797174916, "title"=>"Another film"}, 
#  {"id"=>3, "popularity"=>9.77030797174916, "title"=>"A third film"}] 

或者我還可以使用Enumerable#sort

a = [ 
    { 
    "id"=>1, 
    "popularity"=>7.77030797174916, 
    "title"=>"Another film", 
    }, 
    { 
    "id"=>2, 
    "popularity"=>2.7703074916, 
    "title"=>"A film", 
    }, 
    { 
    "id"=>3, 
    "popularity"=>9.77030797174916, 
    "title"=>"A third film", 
    } 
] 
a.sort{|h1,h2| h1["popularity"] <=> h2["popularity"]} 
# => [{"id"=>2, "popularity"=>2.7703074916, "title"=>"A film"}, 
#  {"id"=>1, "popularity"=>7.77030797174916, "title"=>"Another film"}, 
#  {"id"=>3, "popularity"=>9.77030797174916, "title"=>"A third film"}] 

BENCHMARK

require 'benchmark' 

a = [ 
    { 
    "id"=>1, 
    "popularity"=>7.77030797174916, 
    "title"=>"Another film", 
    }, 
    { 
    "id"=>2, 
    "popularity"=>2.7703074916, 
    "title"=>"A film", 
    }, 
    { 
    "id"=>3, 
    "popularity"=>9.77030797174916, 
    "title"=>"A third film", 
    } 
] 

Benchmark.bm(100) do |b| 
    b.report("Sort") { a.sort{|h1,h2| h1["popularity"] <=> h2["popularity"]} } 
    b.report("Sort by") { a.sort_by{|h| h["popularity"]} } 
end 

       user  system  total  real 
Sort   0.000000 0.000000 0.000000 ( 0.000041) 
Sort by  0.000000 0.000000 0.000000 ( 0.000019) 
相關問題