ruby 数组中的元素是hash,改变一个元素的hash值,为什么所有元素的hash都会改变

Python020

ruby 数组中的元素是hash,改变一个元素的hash值,为什么所有元素的hash都会改变,第1张

终于明白你的意思了。这不是 hash 的问题,是 Array.new 的用法不对,你这样做是指用{}这个对象填充3遍,就是说是同一个对象填充了3次,所以无论你修改哪一个对象,其它的都会跟着变,因为是同一对象。

http://www.ruby-doc.org/core-2.2.0/Array.html#method-c-new-label-Common+gotchas

以上是 ruby 文档,他给出了正确的用法:

a = Array.new(2) { Hash.new }

当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方法进行排序。