在Ruby中,使用’case
‘代替’switch
‘关键字,以及使用’when
‘代替’case
‘关键字。 case
语句将一个语句与多个条件进行匹配,就像其他语言中的switch
语句一样。
语法:
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
代码示例:
#!/usr/bin/ruby
print "Enter your day: "
day = gets.chomp
case day
when "2"
puts '穿红色和白色?'
when "3"
puts 'Wear Green'
when "4"
puts 'Wear Yellow'
when "5"
puts 'Wear White'
when "6"
puts 'Wear Black'
else
puts "Wear Any color"
end
将上面代码保存到文件:case-statement.rb中,执行上面代码,得到以下结果 -
F:\worksp\ruby>ruby case-statement.rb
Enter your day: 3
Wear Any color
F:\worksp\ruby>ruby case-statement.rb
Enter your day: 2
穿红色和白色?
F:\worksp\ruby>ruby case-statement.rb
Enter your day: 3
Wear Green
F:\worksp\ruby>ruby case-statement.rb
Enter your day: 5
Wear White
F:\worksp\ruby>