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


Ruby Set compare_by_identity()用法及代碼示例


compare_by_identity()是Ruby中的一個內置方法,使該集合通過其標識比較其元素並返回self。 Set的所有子類可能不支持此方法。

用法:s1.name.compare_by_identity()

參數:該函數不帶任何參數。


返回值:比較元素後返回self

例子1

#Ruby program to illustrate the compare_by_identity() method 
  
#requires the set 
require "set"
  
    s1 
    = Set[] 
  
#Add 10 to it 
      s1 
      << 10 
  
#Returns self after comparing internally 
         puts s1.compare_by_identity() 
  
             s1 
      << 'a'
  
#Returns self after comparing internally 
         puts s1.compare_by_identity()

輸出

Set:{10}
Set:{10, "a"}

例子2

#Ruby program to illustrate the clear method 
  
#requires the set 
require "set"
  
    s1 
    = Set[] 
  
#Prints s1 
      puts s1 
  
#Add 10 to it 
          s1 
      << 10 
  
         puts s1 
  
#Clears the set and returns self 
#which is printed 
             puts s1.clear

輸出

Set:{}
Set:{10}
Set:{}

參考:https://devdocs.io/ruby~2.5/set#method-i-compare_by_identity



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Ruby | Set compare_by_identity() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。