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.zyzy.cn/article/detail/13426/Ruby