在 Ruby 中,条件判断允许根据不同的条件执行不同的代码块。Ruby 提供了 if、else、elsif 和 unless 等关键字来实现条件判断。

1. if 语句:
# 基本的 if 语句
if condition
  # 如果条件为真执行此块
else
  # 如果条件为假执行此块
end
# 示例
age = 20

if age >= 18
  puts "You are an adult."
else
  puts "You are a minor."
end

2. elsif 语句:
# 多条件判断使用 elsif
if condition1
  # 如果条件1为真执行此块
elsif condition2
  # 如果条件2为真执行此块
else
  # 如果以上条件都为假执行此块
end
# 示例
score = 85

if score >= 90
  puts "Excellent!"
elsif score >= 70
  puts "Good job!"
else
  puts "You need to improve."
end

3. unless 语句:

unless 是与 if 相反的条件判断,当条件为假时执行。
# 使用 unless
unless condition
  # 如果条件为假执行此块
else
  # 如果条件为真执行此块
end
# 示例
temperature = 25

unless temperature > 30
  puts "It's not too hot outside."
else
  puts "It's a hot day!"
end

4. 三元运算符:

三元运算符允许在一行中进行简单的条件判断。
# 三元运算符
condition ? true_expression : false_expression
# 示例
age = 20
status = age >= 18 ? "Adult" : "Minor"
puts status

以上是一些基本的 Ruby 条件判断的示例。根据具体的需求,可以根据不同的条件结构来选择使用哪种形式的条件判断。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13426/Ruby