While below is perfect :
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"}]
Not the below works as expected :
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"}]
Which one is best ruby practice here?
Thanks
The #sort_by block tells the engine which field to use when sorting an
item.
The #sort block gets called with the 2 items being compared and the
block
should return how the items compare (-1, 0, 1).
John
John W Higgins wrote in post #1113860:
The #sort_by block tells the engine which field to use when sorting an
item.
The #sort block gets called with the 2 items being compared and the
block
should return how the items compare (-1, 0, 1).
Thanks for your feed back. Why #sort_by here is faster?
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)
Love U Ruby [email protected] wrote:
Thanks for your feed back. Why #sort_by here is faster?
user system total real
Sort 0.000000 0.000000 0.000000 ( 0.000041)
Sort by 0.000000 0.000000 0.000000 ( 0.000019)
You can’t go by real time – you system could have been doing something
else during the time you ran each benchmark. Notice all the other values
register zero, which means there wasn’t enough time spent in any of them
to make a meaningful benchmark. Run each of your tests 10,000 times,
then see how they compare. (Note: you may still end up with one being
slower than the other; I don’t know. I’m just saying your current
benchmarking is not meaningful enough to make a determination.)