如何使用字符串在Hash中查找对应的Symbol键
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_symtransforms the string"cupcakes"into the Symbol:cupcakes, which is an exact match for the key in yourproductshash.- Ruby’s
key?(and its aliaseshas_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

