EDIT: My bad!!!Problem solved (I tested this on ruby 1.8, worked as expected on ruby 1.9)
I have an existing hash and wanted to sort it such that all the keys will be in numerical order.
a = {4 => 5, 8 => 20, 3 => 2, 6 => 1, 7 => 10, 2 => 1 }
=> #Wanted Newhash = {2 => 1, 3 => 2, 4 => 5, 6 => 1, 7 => 10, 8 => 20 }
Here is what I did:
b = a.keys.sort => [2,3,4,6,7,8]
c ={}
for key in b
p key
c[key] = a[key]
p c
end
Here is the output:
2
{2=>1}
3
{2=>1, 3=>2}
4
{2=>1, 3=>2, 4=>5}
6
{6=>1, 2=>1, 3=>2, 4=>5}
7
{6=>1, 7=>10, 2=>1, 3=>2, 4=>5}
8
{6=>1, 7=>10, 2=>1, 8=>20, 3=>2, 4=>5}
The thing I don't understand is:
The key I sorted in b
is in order that I wanted. I supposed if I added it to a new hash it would be added to the end of the hash but it wasn't the case here. How so? The key 6
with its value got added in the front and the key 7
got added after that and then key 8
with its value was inserted in between key 2
and 3
. Any explanation?
Probably, you are using Ruby < 1.9. That is the reason you did not get the order you wanted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.