0

I use this code for sorting Hash; I've got no idea how its works. please explain to me:

def foo(hash)
  Hash[hash.sort]
end

irb(main):001:0> h = {1=>'z', 3=>'x', 2=>'y'}
=> {1=>"z", 3=>"x", 2=>"y"}
irb(main):002:0> Hash[h.sort]
=> {1=>"z", 2=>"y", 3=>"x"}
irb(main):003:0> 
1
  • This can also be written as Hash[hash.sort_by(&:first)], where hash.sort_by(&:first) sorts the key-value pairs by key. If the hash is large this may be faster than using sort. Commented Nov 22, 2019 at 6:55

1 Answer 1

1

Enumerable#sort reutrns an sorted array of key-value pairs:

h = {b: 1, a: 2}
h.sort
# => [[:a, 2], [:b, 1]]

Hash::[] create a new hash base on the argument:

Hash[h.sort]
# => {:a=>2, :b=>1}

BTW, if you use Ruby 2.1+, you can use Array#to_h instead:

h.sort.to_h
# => {:a=>2, :b=>1}
Sign up to request clarification or add additional context in comments.

3 Comments

For completeness: in ruby v2 you can just do h.sort.to_h
i swear firts things i did was to look in the doc;
@BroiSatse, Thank you for comment. I updated the answer to include Array#to_h. BTW, it's introduced in Ruby 2.1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.