People often ask what is the best way to sort a hash, but then they don\'t ask the needed follow-up question about what is the fastest way, which really determ
This is a comparison of sort
and sort_by
when accessing a more complex object:
require 'fruity'
RUBY_VERSION # => "2.2.2"
class Foo
attr_reader :key
def initialize(k)
@key = k
end
def <=>(b)
self.key <=> b.key
end
end
HASH = Hash[[*(1..100)].shuffle.map{ |k| [Foo.new(k), 1] }]
compare do
_sort1 { HASH.sort.to_h }
_sort_by { HASH.sort_by{ |k,v| k.key }.to_h }
end
# >> Running each test 32 times. Test will take about 1 second.
# >> _sort_by is faster than _sort1 by 2.7x ± 0.1