0

この配列の映画を人気の値で並べ替えたいと思います。これどうやってするの?

[
  { 
    "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",
  }
]
4

2 に答える 2

3

my_array.sort_by { |e| e['popularity'] }

于 2013-06-28T20:17:20.980 に答える
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"}]

基準

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)
于 2013-06-28T20:14:32.260 に答える