Ruby if...else 语句

Ruby 的 if...else 语句用于根据条件是 true 还是 false 来执行/跳过一段代码。

这是一个 if...else 语句的简单示例。你可以阅读本教程的其余部分以了解更多信息。

示例

num = 35

# Check if num is a positive number
if num > 0
  puts "Positive number"
# Else, check if num is negative
elsif num < 0
  puts "Negative number"
# If both conditions fail, num is 0
else
  puts "Zero"
end

# Output: Positive number

在上面的示例中,程序显示

  • 如果 num 大于 0,则显示 正数
  • 如果 num 小于 0,则显示 负数
  • 如果没有任何条件匹配,则显示

Ruby if 语句

我们使用 if 关键字根据某些特定条件执行代码。

if 语句的语法是

if condition 
  # Block of code
end

if 关键字会检查 condition,并根据结果选择要执行的代码。如果 condition 的计算结果为

  • true - 将执行 if 块内的代码。
  • false - 将跳过 if 块内的代码。

请注意语法中的 end 关键字;它用于指示 if 语句的结束。

请记住: 忘记使用 end 关键字会导致错误。

Working of if statement in Ruby
if 语句的工作原理

示例 1:Ruby if 语句

# Program to check if the student passed

score = 96

# Check if score is greater than or equal to 40
if score >= 40
  # The body of the if statement
  puts "You passed the examination."
end

puts "Program executed!"

输出

You passed the examination.
Program executed!

在上面的程序中,条件 score >= 40 的计算结果为 true,因为 score96。因此,将执行 if 语句的主体。

如果分数低于 40(例如 35),则不会执行 if 语句的主体。

最后,由于 puts "Program executed!" 位于 if 语句的主体之外,因此无论 if 语句的结果如何,它都会被执行。

提示: 尝试将 score 的值更改为小于 40 的数字,看看会发生什么。


单行 if 语句

Ruby 也允许你使用单行 if 语句,语法如下

code if condition

在这里,如果 conditiontrue,则会执行 code。例如:

score = 96

puts "You passed!" if score >= 40

# Output: You passed!

在这里,代码 puts "You passed!" 被执行,因为条件 score >= 40true


Ruby else 语句

当前面 if 语句中的条件计算结果为 false 时,else 关键字会执行一段代码。

注意: else 语句应始终跟在 if 语句之后。换句话说,ifelse 语句是单个条件结构的一部分。

if...else 语句的语法是

if condition
  # Block of code to execute if the condition is true
else
  # Block of code to execute if the condition is false
end

if...else 语句会检查 condition,并以两种方式执行代码。如果 condition

  • true - 将执行 if 块内的代码。而 else 块内的代码将被跳过。
  • false - 将跳过 if 块内的代码。相反,将执行 else 块内的代码。
Working of if-else statement in Ruby
if...else 语句的工作原理

示例 2:Ruby if…else 语句

# Program to check if the student passed or failed

score = 35

# Check if score is greater than or equal to 40
if score >= 40
  # The body of the if statement
  puts "You passed the examination."
else
  # The body of the else statement
  puts "You failed the examination."
end

puts "Program executed!"

输出

You failed the examination.
Program executed!

由于 score35,因此 if 条件 (score >= 40) 的计算结果为 false

因此,if 块内的代码被跳过。而 else 块内的代码被执行。


Ruby elsif 语句

如果初始 if 语句为 false,则使用 elsif 关键字来检查其他条件。

注意事项

  • 在 Ruby 中,elsif"else if" 的缩写。
  • if...elsif...else 语句也称为 if...else 梯形图

elsif 语句的语法是

# Check for first condition
if condition1
  # if body

# Check for second condition
elsif condition2
  # elsif body

# If no condition matches
else
  # else body
end

这里

  1. 首先,检查 if 语句中的条件。如果条件计算为 true,则执行 if 的主体,并跳过其余部分。
  2. 否则,将检查 elsif 语句中的条件。如果为 true,则执行其主体,其余部分将被跳过。
  3. 最后,如果没有条件匹配,则执行 else 中的代码块。
Working of if-else ladder statement in Ruby
if...elsif...else 语句的工作原理

示例 3:Ruby if...elsif 语句

score = 59

# Check if score is 80 or above
if score >= 80
  puts "Excellent!"

# Else, check if score is 40 or above
elsif score >= 40
  puts "Average"

# If both conditions fail, you fail the exam
else
  puts "Failure!"
end

# Output: Average

在这里,if 条件为 false,因为 score59。但是,elsif 条件得到满足,因此程序打印 Average


常见问题

如何使用多个 elsif 语句?

我们可以根据需要多次使用 elsif 关键字。例如:

score = 85

# Condition for passing with second division
if score >= 40 && score < 60
  puts "Second division"

# Condition for passing with first division
elsif score >= 60 && score < 80
  puts "First division"

# Condition for passing with distinction
elsif score >= 80 && score <= 100
  puts "Distinction"

# Condition for failing the exam
elsif score > 0 && score < 40
  puts "You failed the examination."

# If all conditions fail, the score is invalid
else
  puts "Invalid score!"
end

# Output: Distinction

在上面的示例中,我们使用了三个 elsif 语句。

第二个 elsif 语句被执行,因为它的条件得到满足,而 if 和第一个 elsif 语句的条件未得到满足。


嵌套 if...else 语句

当我们使用嵌套在另一个 if...else 语句中的 if...else 语句时,我们就创建了一个嵌套 if...else 语句。例如,

score = 60

# Outer if...else statement
# Student passed if score 40 or above
# Otherwise, student failed

if score >= 40

  # Inner if...else statement
  # Distinction if score is 80 or above

  if score >= 80
      puts "Distinction"
  else
      puts "Passed"
  end

else
  puts "Failed"
end

# Output: Passed

外部 if...else 语句

在上面的示例中,外部 if 条件使用 score >= 40 来检查学生是否通过或失败。如果计算结果为 false,则外部 else 语句将打印 "Failed"

另一方面,如果 score >= 40 的计算结果为 true,则程序将进入内部 if...else 语句。

内部 if...else 语句

内部 if 条件使用 score >= 80 来检查学生是否以优异成绩通过。

如果 score >= 80 的计算结果为 true,则内部 if 语句将打印 "Distinction"

否则,内部 else 语句将打印 "Passed"

注意: 为保持代码的可读性并简化调试,请避免将多个 if...else 语句嵌套在一起。


更多关于 Ruby if...else 语句

Ruby 中的真值和假值

被 Ruby 视为 true 的非布尔值称为 truthy,而 视为 false 的称为 falsy

Ruby 将以下值视为 false

  • false
  • nil

其他所有值都被视为 true,包括:

  • 0
  • 空字符串 ("")
  • 空数组 ([])

要了解更多信息,请访问 Ruby 布尔值

什么时候可以使用三元运算符代替 if...else 语句?

如果我们的操作非常简单,我们可以使用 三元运算符 ?: 代替 if...else 语句。例如:

score = 40

result = (score >= 40) ? "pass" : "fail"

puts result

# Output: pass
什么时候可以用 case 语句替换 if...else 语句?

当我们需要处理大量条件时,我们可以用 case 语句替换我们的 if…else 语句。例如:

score = "C"

# Using case statement
case score

# First condition
when "A"
  puts "Excellent!"

# Second condition
when "B"
  puts "Good!"

# Third condition
when "C"
  puts "Average"

# Fourth condition
when "D"
  puts "Bad"

else
  puts "Fail"
end

# Output: Average

如你所见,case 语句使我们的代码更具可读性和可维护性。

如何在单个 if 语句中添加多个条件?

我们可以在 if 语句中使用逻辑运算符,如 &&|| 来添加多个条件。例如,

age = 35
salary = 6000

# Combine two conditions using the "and" operator &&
if age >= 30 && salary >= 5000
  puts "Eligible for premium membership."
else
  puts "Not eligible for premium membership."
end

# Output: Eligible for premium membership.

在这里,我们使用了逻辑运算符 &&if 语句中添加了两个条件。这两个条件是:

  • age >= 30
  • salary >= 5000

由于 && 运算符,必须同时满足这两个条件,if 块才会被执行。

可以使用 if...else 语句检查用户输入吗?

是的,你可以在 if...else 语句中使用用户输入。只需确保你已将输入转换为合适的类型。例如:

print "Enter your exam score: "

# Get user input using gets
user_input = gets.chomp

# Convert the input to integer
score = user_input.to_i

# Check if the user passed or failed
if score >= 40
  puts "pass"
else
  puts "fail"
end

输出 1

Enter your exam score: 56
pass

输出 2

Enter your exam score: 25
fail

在这里,我们使用 gets.chomp 获取用户输入,该输入以字符串形式存储在 user_input 变量中。

因此,我们使用 to_i 方法将输入转换为整数,然后检查用户是否通过或失败。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战