生成带范围的哈希值和nil作为键

时间:2012-01-05 10:46:29

标签: ruby-on-rails ruby

我想创建如下所示的哈希:

{nil => "Cat", 0 => "Dog", 1 => "1", ... 16 => "16"}

这就是我的方式:

hash = { nil => "Cat",0 => "Dog" }
(1..16).to_a.each { |e| hash[e] = e.to_s }

这看起来很难看。有没有更好的方法来实现这一点(在1.8.7版本中)?

由于

1 个答案:

答案 0 :(得分:0)

这不是case的情况吗?

x = 2
res = case x
        when nil   then "cat"
        when 0     then "dog"
        when 1     then "1"
        when 1..16 then x.to_s*2 
      end
p res #=> "22"
相关问题