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

时间:2021-12-03 23:26:35
{:category => 1}.keys.each do |n|
    case n
    when 'category'
        puts 'success'
    else
        puts "failure: #{n}"
    end
end

This ends with "failure: category", and I cannot for the life of me see why, so I'm reasonably sure that I'm doing something enormously stupid.

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

2 个解决方案

#1


1  

try changing when 'category' with when :category

尝试在“类别”时更改时间:类别

#2


2  

You try to compare 'category' string and :category symbol - they are different:

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

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

This should work:

这应该工作:

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

#1


1  

try changing when 'category' with when :category

尝试在“类别”时更改时间:类别

#2


2  

You try to compare 'category' string and :category symbol - they are different:

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

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

This should work:

这应该工作:

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