Ruby范围问题

时间:2012-02-20 17:08:26

标签: ruby range

我在这里搜索范围,但它似乎给我空白结果。

numbers = ["03","03","06","06","06","07","09","10"]

numbers.each do |n|
    result = case n
        when 1..5 then "Jan"
        when 6..10 then "Feb"
    end
    puts result
end

有任何帮助吗? 感谢

1 个答案:

答案 0 :(得分:3)

您拥有的范围是整数范围。为此,您的输入也需要是整数:

numbers = ["03","03","06","06","06","07","09","10"]
numbers.each do |n|
    result = case n.to_i
        when 1..5 then "Jan"
        when 6..10 then "Feb"
    end
    puts result
end

您也可以将其保留为字符串并按此方式执行:

numbers = ["03","03","06","06","06","07","09","10"]
numbers.each do |n|
    result = case n
        when '01'..'05' then "Jan"
        when '06'..'10' then "Feb"
    end
    puts result
end