如何在 Ruby 中使用“or”关键字?


在 Ruby 中,我们使用“or”关键字来返回其两个操作数之间的逻辑差。简单来说,如果两个操作数都为真,则条件变为

  • 如果任何一个条件/表达式为“真”,“or”则返回

  • 只有当所有条件都为“假”时,它才会返回

需要注意的是,or关键字等价于“||”逻辑运算符,但在 Ruby 中其优先级较低。

语法

下面显示了or关键字的语法。

Condition1 or Condition2

让我们在 Ruby 代码中使用or关键字,看看它是如何工作的。

示例 1

请考虑以下代码。

Open Compiler
variable_1 = "Naresh" variable_2 = "Naresh" # Using or keyword if (variable_1 == "naresh" or variable_2 == "N@re$h") puts "Welcome to TutorialsPoint!" else puts "Variables Don't Match! Please Check." end

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

它将在终端中产生以下输出。

Variables Don't Match! Please Check.

在上面的示例中,我们声明了一个if条件,其中我们使用了 or 关键字。

示例 2

现在,让我们使用or关键字和“逻辑或”(||)运算符来查看它们的不同之处,以及在什么情况下应该选择其中一个而不是另一个。请考虑以下代码。

Open Compiler
# and || operator def first_method() true; end def second_method() false; end # Using || operator res1 = first_method || second_method ? "Code in Ruby" : "Code in Java" puts res1 # Using or keyword res2 = first_method or second_method ? "Code in Ruby" : "Code in Java" puts res2

输出

当我们执行此代码时,它将产生以下输出

Code in Ruby
true

在上面的代码中,当我们使用or关键字时,我们注意到得到的输出是,这是因为“=”和“or”关键字的优先级顺序。

当我们使用“逻辑或”(&&)运算符时,它的优先级高于or关键字和“=”运算符,因此我们得到了上述输出。

更新于: 2022年4月12日

1K+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告