当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Ruby Hash.compare_by_identity用法及代码示例

本文简要介绍ruby语言中 Hash.compare_by_identity 的用法。

用法

compare_by_identity → self

设置 self 以在比较键时仅考虑身份;只有当它们是同一个对象时,两个键才被认为是相同的;返回 self

默认情况下,这两个对象被认为是同一个键,所以 s1 将覆盖 s0

s0 = 'x'
s1 = 'x'
h = {}
h.compare_by_identity? # => false
h[s0] = 0
h[s1] = 1
h # => {"x"=>1}

调用#compare_by_identity后,键被认为是不同的,因此不会相互覆盖:

h = {}
h.compare_by_identity # => {}
h.compare_by_identity? # => true
h[s0] = 0
h[s1] = 1
h # => {"x"=>0, "x"=>1}

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Hash.compare_by_identity。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。