📜  和 Ruby 中的关键字

📅  最后修改于: 2022-05-13 01:54:39.744000             🧑  作者: Mango

和 Ruby 中的关键字

Ruby 中的and关键字接受两个表达式,如果两者都为真,则返回“真” ,如果其中一个或多个为假,则返回“假” 。此关键字等效于 Ruby 中的&&逻辑运算符,但优先级较低。 and关键字的主要目的实际上是为了规范控制逻辑流。您可以使用and关键字来链接相互依赖的操作。

句法:

expression1 and expression2  

示例 1:

Ruby
# Ruby program to illustrate and keyword
username = "geek"
password = "come"
 
# Using and keyword
if username == "geek" and password == "come"
puts "Welcome, GeeksforGeeks!"
else 
puts "Incorrect username or password"
end


Ruby
# Ruby program to illustrate and keyword
# and && operator
 
def one() true; end
def two() true; end
 
# Using && operator
res1 = one && two ? "GeeksforGeeks" : "Do Nothing"
puts res1
 
# Using and keyword
res2 = one and two ? "GeeksforGeeks" : "Do Nothing"
puts res2


输出:

Welcome, GeeksforGeeks!

示例 2:

在这个例子中,我们将看到 and 关键字和 &&运算符的优先级差异:

红宝石

# Ruby program to illustrate and keyword
# and && operator
 
def one() true; end
def two() true; end
 
# Using && operator
res1 = one && two ? "GeeksforGeeks" : "Do Nothing"
puts res1
 
# Using and keyword
res2 = one and two ? "GeeksforGeeks" : "Do Nothing"
puts res2

输出:

GeeksforGeeks
true

解释:在上面的例子中,从初级看,逻辑是一样的,但是我们得到不同的结果。因为当你仔细观察时,你会发现差异。第一种情况的输出是GeeksforGeeks ,第二种情况的输出是true 。当然,这与运算符优先级有关。考虑评估它们的顺序(优先级)。

  1. &&
  2. =

在这里, && 比第一条语句中的 = 具有更高的优先级(即,使用 &&运算符)我们有:

res1 = 一 && 二? “GeeksforGeeks”:“什么都不做”

在第二个语句(即 using 和关键字)中,这些操作的顺序不同 = 具有更高的优先级,那么我们有:

res1 = 一和二? “GeeksforGeeks”:“什么都不做”