Ruby - getting value of hash

前端 未结 1 1433
暗喜
暗喜 2020-12-29 03:33

I have a hash like

{:key1 => \"value1\", :key2 => \"value2\"}

And I have a variable k which will have the value as \'

相关标签:
1条回答
  • 2020-12-29 04:07

    Convert the key from a string to a symbol, and do a lookup in the hash.

    hash = {:key1 => "value1", :key2 => "value2"}
    k = 'key1'
    
    hash[k.to_sym] # or iow, hash[:key1], which will return "value1"
    

    Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases. I know that you've only tagged your question with Ruby, but you could steal the implementation of this class from Rails' source to avoid string to symbol and symbol to string conversions throughout your codebase. It makes the value accessible by using a symbol or a string as a key.

    hash = HashWithIndifferentAccess.new({:key1 => "value1", :key2 => "value2"})
    hash[:key1]  # "value1"
    hash['key1'] # "value1"
    
    0 讨论(0)
提交回复
热议问题