本文簡要介紹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 Hash.compact用法及代碼示例
- Ruby Hash.compact!用法及代碼示例
- Ruby Hash.reject用法及代碼示例
- Ruby Hash.delete()用法及代碼示例
- Ruby Hash.new用法及代碼示例
- Ruby Hash.size用法及代碼示例
- Ruby Hash.delete用法及代碼示例
- Ruby Hash.hash <=用法及代碼示例
- Ruby Hash.select!用法及代碼示例
- Ruby Hash.ruby2_keywords_hash用法及代碼示例
- Ruby Hash.rassoc(obj)用法及代碼示例
- Ruby Hash.to_s用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.select用法及代碼示例
- Ruby Hash.initialize_copy用法及代碼示例
- Ruby Hash.replace用法及代碼示例
- Ruby Hash.merge!用法及代碼示例
- Ruby Hash.delete_if用法及代碼示例
- Ruby Hash.slice用法及代碼示例
- Ruby Hash.hash用法及代碼示例
- Ruby Hash.each_value用法及代碼示例
- Ruby Hash.fetch()用法及代碼示例
- Ruby Hash.each用法及代碼示例
- Ruby Hash.keys用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Hash.compare_by_identity。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。