You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字符串在Hash中查找对应的Symbol键

How to Check for a Symbol Key Using a String in Ruby Hash

Got it, let's sort this out quickly. The core issue here is that Ruby's Hash key? method checks for exact matches—including data type. Your category is a String ("cupcakes"), but the keys in your products hash are Symbols (:cupcakes), so they don't register as a match right out of the gate.

The Straightforward Fix: Convert the String to a Symbol

The simplest solution is to turn your string category into a Symbol using the to_sym method. This makes the type match the keys in your hash, so key? will work as expected:

category = "cupcakes"
products = { 
  :cupcakes => [{:title => "chocolate", :flavor => "chocolate"}, {:title => "summer special", :flavor => "pink cake"}], 
  :cookies => [{:title => "chocolate bliss", :flavor => "chocolate chip"}, {:title => "breakfast surprise", :flavor => "oatmeal raisin"}] 
}

# Now this will correctly return true
products.key?(category.to_sym)

Why This Works

  • category.to_sym transforms the string "cupcakes" into the Symbol :cupcakes, which is an exact match for the key in your products hash.
  • Ruby’s key? (and its aliases has_key?/include?) only recognizes matches when both the value and data type are identical—so converting the string fixes the mismatch.

Bonus: Flexible Check for Mixed Key Types

If you ever need to handle a hash that might have both String and Symbol keys, you can use a more adaptable check:

# Check if any key (converted to string) matches your category
products.keys.any? { |key| key.to_s == category }

This way, even if the hash had a String key "cupcakes" instead of :cupcakes, it would still return true. But for your specific use case, the first solution is the cleanest and most efficient.

内容的提问来源于stack exchange,提问作者Maiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:55