Can you please help anyone?. I have a hash value as following. I need to sort the hash in reverse order by key value and return as also hash type.
My actual expected output is (hash)
result = {20111104111221=>[4, 5, 6], 20111104111220=>[7, 8, 9], 20111104110950=>[1, 2, 3]}
# this is my input
irb(main):096:0> h = {20111104111221=>[4, 5, 6], 20111104110950=>[1, 2, 3], 20111104111220=>[7, 8, 9]}
=> {20111104111221=>[4, 5, 6], 20111104110950=>[1, 2, 3], 20111104111220=>[7, 8, 9]}
# It's not correct
irb(main):095:0> Hash[h.sort]
=> {20111104111221=>[4, 5, 6], 20111104110950=>[1, 2, 3], 20111104111220=>[7, 8, 9]}
So, i tried this. It’s correct but it’s return as a array value, i need a return value as Hash.
# It's correct but it's not a hash
irb(main):092:0> arr = h.sort_by { |k,v| k }.reverse
=> [[20111104111221, [4, 5, 6]], [20111104111220, [7, 8, 9]], [20111104110950, [1, 2, 3]]]
Again i tried array to hash conversion.. but it’s help.
# It's also not correct.
irb(main):092:0> irb(main):098:0> Hash[*arr.flatten]
=> {5=>6, 20111104111221=>4, 20111104110950=>1, 2=>3, 8=>9, 20111104111220=>7}
Which version of ruby are you using? In 1.8 hashes cannot be ordered, in 1.9 they are ordered based on insertion. Here’s more info on that.
Given the variation in how they’re handled I wouldn’t focus on sorting the hash itself, but on sorting your keys and using them as a reference, something like:
The debug line is in there just as an example of how to access your values. Hope this helps!