红宝石 |设置 compare_by_identity()函数
compare_by_identity()是 Ruby 中的一个内置方法,它使集合通过其身份比较其元素并返回 self。 Set 的所有子类可能不支持此方法。
Syntax: s1.name.compare_by_identity()
Parameters: The function does not takes any parameter.
Return Value: It returns self after comparing its elements.
示例 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