Ruby/Statement/case
Материал из Wiki.crossplatform.ru
Версия от 18:00, 13 сентября 2010; ViGOur (Обсуждение | вклад)
All Ruby expressions return a result
# you assign the result of whichever inner block is executed directly to color. fruit = "orange" color = case fruit when "orange" "orange" when "apple" "green" when "banana" "yellow" else "unknown" end
case...when with range
#!/usr/bin/env ruby scale = 8 case scale when 0: puts "lowest" when 1..3: puts "medium-low" when 4..5: puts "medium" when 6..7: puts "medium-high" when 8..9: puts "high" when 10: puts "highest" else puts "off scale" end
Case with regular expression
string = "123" case string when /^[a-zA-Z]+$/ "Letters" when /^[0-9]+$/ "Numbers" else "Mixed" end # => "Numbers"
elsif and case
fruit = "orange" if fruit == "orange" color = "orange" elsif fruit == "apple" color = "green" elsif fruit == "banana" color = "yellow" else color = "unknown" end fruit = "orange" case fruit when "orange" color = "orange" when "apple" color = "green" when "banana" color = "yellow" else color = "unknown" end
Here"s the general format of the Ruby case statement:
case value when expression [, comparison]...[then | :] code when expression [, comparison]...[then | :] code . . . [else code] end
If vs Case
command = "Stop" case command when "Go" puts "Going" when "Wait" puts "Waiting" when "Turn" puts "Turning" when "Stop" puts "Stopping" else puts "I can"t understand that." end # This example also could be written as an if statement with a collection of elsif and else clauses: command = "Stop" if command == "Go" puts "Going" elsif command == "Wait" puts "Waiting" elsif command == "Turn" puts "Turning" elsif command == "Stop" puts "Stopping" else puts "I can"t understand that." end
use a case statement to make an assignment, which omits the value to test
temperature = 76 message = case when (0...65) === temperature "Too cold!" when (85...120) === temperature "Too hot!" when (65...85) === temperature "Picnic time!" else "Temperature out of reasonable range!" end puts message
use exculsive ranges in case statements
temperature = 76 case temperature when 0...65 puts "Too cold!" when 85...120 puts "Too hot!" when 65...85 puts "Picnic time!" else puts "Temperature out of reasonable range!" end
Using the case Statement
command = "Stop" case command when "Go" puts "Going" when "Wait" puts "Waiting" when "Turn" puts "Turning" when "Stop" puts "Stopping" else puts "I can"t understand that." end