如何用Ruby编写开关语句
/
猿问
case
case xwhen 1..5 "It's between 1 and 5"when 6 "It's 6"when "foo", "bar" "It's either foo or bar"when String "You passed a string"else "You gave me #{x} -- I have no idea what to do with that."end
when
case
===
1..5 === x
x === 1..5
.
when
switch
case
when
break
when
when "foo", "bar"
.
case...when
===
1 === 1 # => trueFixnum === Fixnum # => false
case ... when
obj = 'hello'case obj.classwhen String print('It is a string')when Fixnum print('It is a number')else print('It is not a string')end
===
true
Fixnum === 1 # => true
.class
:
obj = 'hello'case obj # was case obj.classwhen String print('It is a string')when Fixnum print('It is a number')else print('It is not a string')end
case nwhen 0 puts 'You typed zero'when 1, 9 puts 'n is a perfect square'when 2 puts 'n is a prime number' puts 'n is an even number'when 3, 5, 7 puts 'n is a prime number'when 4, 6, 8 puts 'n is an even number'else puts 'Only single-digit numbers are allowed'end
score = 70result = case score when 0..40 then "Fail" when 41..60 then "Pass" when 61..70 then "Pass with Merit" when 71..100 then "Pass with Distinction" else "Invalid Score"endputs result
then
when
if then else
then
举报