问题是要找出某个元素是否存在于指定集中?我们正在尝试通过两种逻辑来执行此任务。解决方案有很多替代方案,但在这里我们仅关注两个替代方案。让我们看看如何找到解决方案。
使用的方法:
===:此运算符是.include的别名?方法,并返回true或false。
set.each:此方法用于处理集合中的单个元素。
set.include?():此方法返回true或false。这用于检查集合中元素的存在。
使用的变量:
Vegetable:这是Set类的实例。
element:它包含用户输入的字符串。
程序1:
=begin Ruby program to find the presence of an element in a set. =end require 'set' Vegetable=Set.new(["potato","brocolli","broccoflower","lentils","peas","fennel","chilli","cabbage"]) puts "Enter the element:-" element = gets.chomp val = Vegetable === element if val == true puts "#{element} is Present in the set." else puts "#{element} is not Present in the set." end
输出结果
RUN 1: Enter the element:- tomato tomato is not Present in the set. RUN 2: Enter the element:- peas peas is Present in the set.
说明:
在上面的代码中,我们从用户那里获取输入,该输入不过是我们要搜索的元素。我们在这里从===运算符获取帮助。在此运算符的帮助下,我们无需使用任何循环并处理单个元素。我们的任务借助===运算符以几行代码完成。
程式2:
=begin Ruby program to find the presence of an element in a set. =end require 'set' Vegetable=Set.new(["potato","brocolli","broccoflower","lentils","peas","fennel","chilli","cabbage"]) puts "Enter the element:-" element = gets.chomp val1 = false Vegetable.each do |string| if string == element val1 = true end end if val1 == true puts "#{element} is present in the set." else puts "#{element} is not present in the set." end
输出结果
RUN 1: Enter the element:- tomato tomato is not Present in the set. RUN 2: Enter the element:- peas peas is Present in the set.
说明:
在上面的代码中,我们正在测试集合中的每个元素,并将检查它是否与用户输入的元素匹配。如果与元素匹配,则将标志设置为true。以后,如果发现该标志为true,则在控制台上打印该字符串,通知该元素的存在,如果该元素不存在,则在控制台上打印一条消息,告知该元素不可用。
程式3:
=begin Ruby program to find the presence of an element in a set. =end require 'set' Vegetable=Set.new(["potato","brocolli","broccoflower","lentils","peas","fennel","chilli","cabbage"]) puts "Enter the element:-" element = gets.chomp if Vegetable.include?(element) puts "#{element} is present" else puts "#{element} is not present" end
输出结果
RUN 1: Enter the element:- peas peas is present RUN 2: Enter the element:- onion onion is not present
说明:
在上面的代码中,我们正在使用set.include?检查用户输入的元素是否存在的方法。这使任务非常简单,并使我们的代码更高效。借助这种方法,我们还减少了代码行。