Ruby 判断
Ruby 提供了几种很常见的条件结构。在这里,我们将解释所有的条件语句和 Ruby 中可用的修饰符。
Ruby if...else 语句
if 表达式用于条件执行。值 false 和 nil 为假,其他值都为真。请注意,Ruby 使用 elsif,不是使用 else if 和 elif。
如果 conditional 为真,则执行 code。如果 conditional 不为真,则执行 else 子句中指定的 code。
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
x=1
if x < 1
puts "x 小于 1"
elsif x >= 1 && x < 2
puts "x 等于 1"
else
puts "x 大于 1"
end
Ruby if 修饰符
语法
code if true / false
Ruby unless 语句
语法
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
x = 1
unless x > 2
puts "NO"
else
puts "YES"
end
Ruby unless 修饰符
语法
code unless true/false
Ruby case 语句
语法
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
case先对一个 expression 进行匹配判断,然后根据匹配结果进行分支选择。
它使用 ===运算符比较 when 指定的 expression,若一致的话就执行 when 部分的内容。
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
age = 6
msg = "小孩"
case
when age < 6
msg = "婴儿"
when age < 12
msg = "少年"
else age < 18
msg = "其他"
end
puts msg
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
age = 8
msg = "小孩"
case age
when 0 .. 2
msg = "婴儿"
when 3 .. 6
msg = "小孩"
when 7 .. 12
msg = "儿童"
when 13 .. 17
msg = "少年"
else
msg = "成年人"
end