Skip to content

Ruby IF...ELSE 条件语句

Ruby 条件逻辑:if, else, case, unless

Section titled “Ruby 条件逻辑:if, else, case, unless”

条件结构允许你的程序根据某些条件是真(true)还是假(false)来做出决策并执行不同的代码块。Ruby 提供了几种表达条件逻辑的方式。

Ruby 中的真值(Truthiness)和假值(Falsiness):

Section titled “Ruby 中的真值(Truthiness)和假值(Falsiness):”

在 Ruby 中,只有两个值被认为是“假值(falsey)”:

  • false (布尔值 false)
  • nil (代表没有值)

其他所有值,包括 0、空字符串 "" 和空数组 [],都被认为是“真值(truthy)”。这是理解条件语句的关键概念。

这是有条件执行代码的标准方式。

语法:

if condition1 [then]
# code to execute if condition1 is true
elsif condition2 [then]
# code to execute if condition1 is false and condition2 is true
else
# code to execute if all preceding conditions are false
end

then 关键字是可选的,特别是当代码块在新的一行开始时。Ruby 使用 elsif (而不是 else if 或 elif)。

示例:

#!/usr/bin/ruby
score = 75
if score >= 90
puts "Grade: A"
elsif score >= 80
puts "Grade: B"
elsif score >= 70
puts "Grade: C"
elsif score >= 60
puts "Grade: D"
else
puts "Grade: F"
end
# Example demonstrating truthiness
# 演示真值的示例
an_empty_string = ""
if an_empty_string
puts "An empty string is truthy in Ruby!"
end

输出:

Grade: C
An empty string is truthy in Ruby!

对于单行条件执行,你可以将 if 放在语句的末尾。

语法:

statement if condition

示例:

#!/usr/bin/ruby
logged_in = true
puts "Welcome back!" if logged_in
temperature = 30
puts "It's hot!" if temperature > 28

输出:

Welcome back!
It's hot!

如果条件为假,则执行代码。它与 if 相反。

语法:

unless condition [then]
# code to execute if condition is false
else
# code to execute if condition is true (optional)
end

示例:

#!/usr/bin/ruby
is_raining = false
unless is_raining
puts "Let's go for a walk!"
else
puts "Better stay indoors."
end

输出:

Let's go for a walk!

Ruby unless 修饰符(postfix unless):

Section titled “Ruby unless 修饰符(postfix unless):”

类似于 if 修饰符,用于条件为假时的单行条件执行。

语法:

statement unless condition

示例:

#!/usr/bin/ruby
error_occurred = false
puts "All systems nominal." unless error_occurred

输出:

All systems nominal.

case 语句对于将一个变量与多个值或条件进行比较非常有用。它使用 ===(case equality 或 triple equals)运算符进行比较,这比 == 更具通用性。

语法:

case expression
when value1 [, value2,...] [then]
# code for value1 or value2
when value3 [then]
# code for value3
else
# code if no when clause matches (optional)
end

case 后面的 expression 是可选的。如果省略,when 子句会将它们的条件作为布尔表达式进行评估。

case 语句和不同 when 条件的示例:

#!/usr/bin/ruby
def assess_value(value)
case value
when 0..10
puts "#{value} is a small number (0-10)."
when String
puts "'#{value}' is a String."
when /^[A-Z]/ # Regex: starts with an uppercase letter
# 正则表达式:以大写字母开头
puts "'#{value}' seems to be a capitalized identifier."
when :active, :pending # Multiple specific symbols
# 多个特定的 Symbol
puts "Status is #{value}."
else
puts "#{value.inspect} is something else."
end
end
assess_value(5)
assess_value("hello")
assess_value("ErrorCode") # Matches regex, but String matches first if not reordered
# 匹配正则表达式,但如果when顺序不变,String会先匹配到
assess_value(:pending)
assess_value([1, 2, 3])
puts "--- Case without an expression ---"
# --- 没有 expression 的 Case 语句 ---
def check_permissions(user_role)
case
when user_role == :admin
puts "Full access granted."
when user_role == :editor
puts "Can create and edit content."
else
puts "Read-only access."
end
end
check_permissions(:admin)

输出:

5 is a small number (0-10).
'hello' is a String.
'ErrorCode' is a String.
Status is pending.
[1, 2, 3] is something else.
--- Case without an expression ---
Full access granted.

=== 运算符功能强大。例如,(0..10) === 5 为真,String === "hello" 为真,而 /pattern/ === "string" 则检查字符串是否匹配正则表达式。

对于简单的 if/else 逻辑来为一个变量赋值,三元运算符提供了一种简洁的替代方式。

语法:

result = condition ? value_if_true : value_if_false

示例:

#!/usr/bin/ruby
age = 20
status = age >= 18 ? "Adult" : "Minor"
puts "Status: #{status}" # Output: Status: Adult
# 输出: Status: Adult

实际应用:

条件逻辑是程序流程的基石。它用于:验证用户输入、根据权限控制访问、处理应用程序的不同状态、实现业务规则、定制输出等等。在 if/elsif/else、case 或修饰符之间进行选择取决于所需的复杂性和可读性。