當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。