Ruby Case語句
在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>