Ruby 中什么样的 Hash 会相等?
为情所困
为情所困 2017-04-24 15:59:46
0
2
661
hash1 = {:one=>1,:two=>2}
hash2 = {:two=>2,:one=>1}
hash1 == hash2
=> true
assert_equal hash1, hash2
=> true
hash1.object_id == hash2.object_id
=> false

这个情况下hash1和hash2明显不是同一个对象为什么可以assert_equal?

hash = { "jim" => 53, "amy" => 20, "dan" => 23 }
new_hash = hash.merge({ "jim" => 54, "jenny" => 26 })
expected = { "jim" => 53, "amy" => 20, "dan" => 23, "jenny" => 26 }
expected == new_hash
=> false

这个情况下为什么expected和new_hash又不等了?

还有一个,求大神解释一下:

hash = Hash.new {|hash, key| hash[key] = [] }

这句话是什么意思?这个语法是怎么回事?三个hash一样么?

为情所困
为情所困

reply all(2)
伊谢尔伦

1, Hash#==方法, 当两个哈希有相同数目的键值对, 且键值对根据自身的#==method determines equality, then the two hashes are equal

Description:

  • :one=>1就是键值对, :one为符号, 为键, 1为整数, 为值. Ruby中的符号是全局唯一的, 即:one就只有一个, 自然彼此相等, 1 is an integer, and the equality judgment is also very intuitive.

  • Ruby’s judgment is pending, #==方法会被子类覆盖, 提供语义的相等, 如1==1.0true. 而#equal?禁止覆盖, 比较对象的#object_id, 即只有同一个对象才equal, 如1.equal? 1.0false. 题主应该说的是#equal?.

2, the value of Hash#merge方法, 如h1.merge h2, 对于相同的键, h1会被h2中覆盖. 即new_hash["jim"]为54. 你可以让h2 merge h1, 如果你想要h1. Or, as follows

new_hash = hash.merge({"jim"=>54, "jenney"=>26}) {|key, oldval, newval| oldval}
new_hash == expected  #=> true

3, Hash.new主要处理的是, 当索引不存在的键时, 哈希应该返回什么值, 如hash1['not_exist_key']. 此处, |hash, key|中, hash即为hash1, 即调用对象, key'not_exist_key'. 此语句的意思是, 当索引不存在的键时, 返回空数组[], 更简单的写法是hash = Hash.new([]).

刘奇

expected and new_hash are not equal because one jim is 53 and the other jim is 54!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template