-1

The code is as below, and I am trying to understand that this specific code does to_a.sort_by(&:hash).hash in the Hash.hash method. What I do know is that, it first turns the hash into an array, sort the array, and then call the hash method on the Array class. I am trying to understand how exactly was the array sorted by?

class Fixnum
  # Fixnum#hash already implemented for you
end

class Array
  def hash
    each_with_index.inject(0) do |intermediate_hash, (el, i)|
      (el.hash + i.hash) ^ intermediate_hash
    end
  end
end

class Hash
  def hash
    to_a.sort_by(&:hash).hash
  end
end
Yes
  • 63
  • 5

1 Answers1

0

This is syntactic sugar for Symbol#to_proc.

In your concrete case the expansion would look like this:

to_a.sort_by { |e| e.hash }.hash

It other words it's sort the array by the hash value of its elements.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158