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)”。这是理解条件语句的关键概念。
Ruby if...elsif...else 语句:
Section titled “Ruby if...elsif...else 语句:”这是有条件执行代码的标准方式。
语法:
if condition1 [then] # code to execute if condition1 is trueelsif condition2 [then] # code to execute if condition1 is false and condition2 is trueelse # code to execute if all preceding conditions are falseendthen 关键字是可选的,特别是当代码块在新的一行开始时。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: CAn empty string is truthy in Ruby!Ruby if 修饰符(postfix if):
Section titled “Ruby if 修饰符(postfix if):”对于单行条件执行,你可以将 if 放在语句的末尾。
语法:
statement if condition示例:
#!/usr/bin/ruby
logged_in = trueputs "Welcome back!" if logged_in
temperature = 30puts "It's hot!" if temperature > 28输出:
Welcome back!It's hot!Ruby unless 语句:
Section titled “Ruby unless 语句:”如果条件为假,则执行代码。它与 if 相反。
语法:
unless condition [then] # code to execute if condition is falseelse # 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 = falseputs "All systems nominal." unless error_occurred输出:
All systems nominal.Ruby case 语句:
Section titled “Ruby case 语句:”case 语句对于将一个变量与多个值或条件进行比较非常有用。它使用 ===(case equality 或 triple equals)运算符进行比较,这比 == 更具通用性。
语法:
case expressionwhen value1 [, value2,...] [then] # code for value1 or value2when value3 [then] # code for value3else # code if no when clause matches (optional)endcase 后面的 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." endend
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." endend
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" 则检查字符串是否匹配正则表达式。
三元条件运算符 (? :):
Section titled “三元条件运算符 (? :):”对于简单的 if/else 逻辑来为一个变量赋值,三元运算符提供了一种简洁的替代方式。
语法:
result = condition ? value_if_true : value_if_false示例:
#!/usr/bin/ruby
age = 20status = age >= 18 ? "Adult" : "Minor"puts "Status: #{status}" # Output: Status: Adult # 输出: Status: Adult实际应用:
条件逻辑是程序流程的基石。它用于:验证用户输入、根据权限控制访问、处理应用程序的不同状态、实现业务规则、定制输出等等。在 if/elsif/else、case 或修饰符之间进行选择取决于所需的复杂性和可读性。