为什么说ruby中hash是无序的

Python016

为什么说ruby中hash是无序的,第1张

当values都是整形时,按照Hash的Values排序:

h = {'a'=>1,'b'=>2,'c'=>5,'d'=>4}

h.sort {|a,b| a[1]<=>b[1]}

输出:[["a", 1], ["b", 2], ["d", 4], ["c", 5]]

当我们需要对Hash进行排序时,不能像数组那样简单的使用sort方法,因为数组中的数据类型都是一样的(整型),Hash中的数据类型可能并不完全一样,如整数类型和字符串类型就没法一起排序,此时就需要我们进行处理,如下(如果Hash中的数据类型全部相同可以不进行如下处理):

def sorted_hash(aHash)

return aHash.sort{

|a,b| a.to_s <=>b.to_s

}

End

h1 = {1=>'one', 2=>'two', 3=>'three'}

h2 = {6=>'six', 5=>'five', 4=>'four'}

h3 = {'one'=>'A', 'two'=>'B','three'=>'C'}

h4 = h1.merge(h2) #合并hash

h5 = h1.merge(h3)

def sorted_hash(aHash)

return aHash.sort{|a,b| a.to_s <=>b.to_s }

end

p(h4)

p(h4.sort)

p(h5)

p(sorted_hash(h5))

----------------Result---------------

{5=>"five", 6=>"six", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}

[[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"], [6, "six"]]

{"two"=>"B", "three"=>"C", 1=>"one", 2=>"two", "one"=>"A", 3=>"three"}

[[1, "one"], [2, "two"], [3, "three"], ["one", "A"], ["three", "C"], ["two", "B"]]

事实上Hash的sort方法是把一个Hash对象转换成以[key,value]为单个元素的一个数组,然后再用数组的sort方法进行排序。

ruby的汉语意思如下:

n.

红宝石深红色。

adj.

红宝石的红宝石色的。

ruby的读音是:英 [ˈruːbi]   美 [ˈruːbi] 。

ruby的造句如下:

1、RDT is a far more full-featured Ruby IDE with a ton of exciting and time-saving options.

RDT是一个功能更为完善的Ruby开发环境,具备许多令人兴奋并且可以节省大量开发时间的选项。

2、Rich ruby color with tastes of black cherry, full plum and soft vanilla and toffee notes.

酒体呈漂亮的宝石红色,富含蓝莓和熟李子的果香,以及优雅的香草及太妃糖香气。

3、Download and install Ruby libraries easily.

容易地下载和安装ruby库。

4、Tasting notes: A bright ruby red colour with attractive purple hues.

品酿笔记:酒泽如红宝石般明亮动人,但又透露著 * 紫色于其中。

5、Deep ruby coloured with purple reflections in the first years and tending to orange when older.

深宝石红,年轻时泛紫色边缘,随着时间变化会慢慢转成橘黄色。

6、The origin of Ruby Fall.

红宝石瀑布的起源.