Ruby/Hash/sort

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Sort a hash

myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" }
p myHash # => {5=>"Five", 1=>"One", 2=>"Two", 3=>"Three", 4=>"Four"}
myHash.sort # => [[1, "One"], [2, "Two"], [3, "Three"], [4, "Four"], [5, "Five"]]
p myHash



When you sort a hash with the sort method, you get a multidimensional array of two-element arrays in return.

myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 =>"Four", 5 => "Five" }
p myHash 
p myHash.sort 
# Hash does not have a sort! method, to change the contents of the hash in place.