使用带有'和'关键字的Ruby的case语句的正确方法

时间:2013-08-05 18:19:58

标签: ruby switch-statement

在ruby的case语句中使用'and'关键字的正确方法是什么? 这是一个例子:

编写一个询问用户年龄的程序,并根据输入打印以下字符串:

0 to 2      =>     "baby"
3 to 6      =>     "little child"
7 to 12     =>     "child"
13 to 18    =>     "youth"
18+         =>     "adult"

示例1

INPUT
Enter the age:
3
OUTPUT
little child*

puts "Enter the age:" 
age = gets.chomp.to_i
#Write your code here 
case (age)
    when age >= 0 and <= 2      then puts("baby")
    when age > 2 and < 7        then puts("little child")
    when age > 6 and < 13       then puts("child")
    when age > 12 and < 18      then puts("youth")
    when age > 18               then puts("adult")
end

1 个答案:

答案 0 :(得分:0)

1)&lt;,&lt; = etc需要'对象',如两边的数字或字符串 2)在Chuck从other question(年龄> = 0且年龄<= 2)的答案的帮助下,评估为true然后将此true与年龄进行比较:age === true这让你虚假 您可以在案例陈述中使用ranges case age
when 0..2 then puts 'baby' #with 2 dots, it will check 0, 1, 2
when 3...7 then puts 'little child' #with 3 dots, it will check 3, 4, 5, 6[no 7!]
when 7...13 then puts 'child'
when 13...18 then puts 'youth'
when 19..120 then puts 'adult'