Ruby - getting value of hash

江枫思渺然 提交于 2019-11-29 01:46:00

问题


I have a hash like

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

And I have a variable k which will have the value as 'key1' or 'key2'.

I want to get the value of k into a variable v.

Is there any way to achieve this with out using if or case? A single line solution is preferred. Please help.


回答1:


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"


来源:https://stackoverflow.com/questions/8676531/ruby-getting-value-of-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!