如何在 Ruby 中使用“and”关键字?
'and' 关键字在 Ruby 中
在 Ruby 中,我们使用“and”关键字,如果两个操作数都为真,则返回True,如果一个或多个操作数为假,则返回False。需要注意的是,and 关键字等效于&&逻辑运算符,但在 Ruby 中优先级较低。
语法
and关键字的语法如下所示。
expression1 and expression2
让我们在 Ruby 代码中使用and关键字,看看它是如何工作的。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
请考虑以下代码。
variable1 = "sunshine" variable2 = "$un$h1ne" # Using and keyword if (variable1 == "sunshine" and variable2 == "$un$h1ne") puts "Learn Ruby Programming" else puts "Variables Don't Match!" end
输出
它将产生以下输出。
Learn Ruby Programming
'and' 和 '&&'(逻辑与)运算符在 Ruby 中
现在,让我们将and关键字与逻辑与(&&)运算符一起使用,看看它们有什么不同,以及在什么情况下应该选择其中一个而不是另一个。请考虑以下代码。
示例
请考虑以下代码。
# and && operator def first() true; end def second() true; end # Using && operator res1 = first && second ? "TutorialsPoint" : "Do Nothing" puts res1 # Using and keyword res2 = first and second ? "TutorialsPoint" : "Do Nothing" puts res2
输出
如果我们在任何 Ruby IDE 上编写以下代码,那么我们将在终端中获得以下输出。
TutorialsPoint true
在上面的代码中,当我们使用 and 关键字时,我们得到的输出是“true”,这是因为“=”和“and”关键字的优先级顺序。
另一方面,当我们使用“&&”运算符时,我们得到“TutorialsPoint”作为输出。这是因为“逻辑与”运算符(&&)的优先级高于“and”关键字,也高于“=”运算符。
广告