Ruby提供了各种方法,通过它们可以在两组中执行比较操作。现在,让我们看一下各种方法,并借助它们的语法和示例了解它们的实现。
当两个集合相等时,该运算符将返回true;或者您可以说,要使该值为true,set2必须具有与set1相同的值。
语法:
Set1 == Set2
示例
=begin Ruby program to show == =end require 'set' Vegetable = Set.new(["potato", "tomato","brinjal","onion"]) Sabzi = Set.new(["potato", "tomato","brinjal","onion"]) bool = Vegetable == Sabzi if bool == true puts "Vegetable is equal to Sabzi" else puts "Vegetable is not equal to Sabzi" end
输出结果
Vegetable is equal to Sabzi
该运算符是适当子集的别名。当Set2具有Set1中存在的所有元素时,此运算符将返回true。Set2可能有也可能没有更多元素。
语法:
Set2 < Set1
示例
=begin Ruby program to show < operator =end require 'set' Vegetable = Set.new(["potato" , "tomato" , "brinjal" , "onion"]) Sabzi = Set.new(["potato" , "tomato" , "brinjal" , "onion" , "beetroot"]) bool = Vegetable < Sabzi if bool == true puts "Vegetable is a subset of Sabzi" else puts "Vegetable is not a subset to Sabzi" end
该运算符是适当超集的别名。当Set1具有Set2中存在的所有元素时,此运算符将返回true。Set1可以具有或可以不具有更多元素。
语法:
Set2 > Set1
示例
=begin Ruby program to show > operator =end require 'set' Vegetable = Set.new(["potato", "tomato","brinjal","onion"]) Sabzi = Set.new(["potato", "tomato","brinjal","onion","beetroot"]) bool = Vegetable > Sabzi if bool == true puts "Vegetable is a superset of Sabzi" else puts "Vegetable is not a superset of Sabzi" end
输出结果
Vegetable is not a superset of Sabzi
该运算符是适当超集的别名。当Set1具有Set2中存在的所有元素时,此运算符将返回true。Set1可以具有或可以不具有更多元素。
语法:
set1.subset?(set2)
示例
=begin Ruby program to show subset method =end require 'set' Vegetable = Set.new(["potato", "tomato","brinjal","onion","peas"]) Sabzi = Set.new(["potato", "tomato","brinjal","onion","beetroot"]) bool = Vegetable.subset?(Sabzi) if bool == true puts "Vegetable is a subset of Sabzi" else puts "Vegetable is not a subset of Sabzi" end
输出结果
Vegetable is not a subset of Sabzi
此方法的工作方式与<运算符相同,因为>运算符是此方法的别名。此方法以以下方式实现:
语法:
set1.superset?(set2)
示例
=begin Ruby program to show superset method =end require 'set' Vegetable = Set.new(["potato", "tomato","brinjal","onion","peas","beetroot"]) Sabzi = Set.new(["potato", "tomato","brinjal","onion","beetroot"]) bool = Vegetable.superset?(Sabzi) if bool == true puts "Vegetable is a superset of Sabzi" else puts "Vegetable is not a superset of Sabzi" end
输出结果
Vegetable is a superset of Sabzi