迭代hash.keys并通过case / when运行

时间:2013-10-22 10:39:37

标签: ruby-on-rails ruby

{:category => 1}.keys.each do |n|
    case n
    when 'category'
        puts 'success'
    else
        puts "failure: #{n}"
    end
end

这以“失败:类别”结束,我不能为我的生活看到原因,所以我有理由相信我做了一些非常愚蠢的事情。

2 个答案:

答案 0 :(得分:2)

您尝试比较'category'字符串和:category符号 - 它们是不同的:

'category' === :category
# => false

这应该有效:

{:category => 1}.keys.each do |n|
  case n
  when :category
    puts 'success'
  else
    puts "failure: #{n}"
  end
end

答案 1 :(得分:1)

尝试使用when 'category'

更改when :category