Ruby - 获取哈希值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8676531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby - getting value of hash
提问by Sayuj
I have a hash like
我有一个像
{:key1 => "value1", :key2 => "value2"}
{:key1 => "value1", :key2 => "value2"}
And I have a variable kwhich will have the value as 'key1'or 'key2'.
我有一个变量k,其值为'key1'or 'key2'。
I want to get the value of kinto a variable v.
我想将 的值k放入一个变量中v。
Is there any way to achieve this with out using ifor case? A single line solution is preferred. Please help.
有没有办法在不使用ifor 的情况下实现这一目标case?首选单线解决方案。请帮忙。
回答by Anurag
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 HashWithIndifferentAccessthat 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.
Rails 使用这个被HashWithIndifferentAccess证明在这种情况下非常有用的类。我知道您只用 Ruby 标记了您的问题,但是您可以从 Rails 的源代码中窃取此类的实现,以避免在整个代码库中进行字符串到符号和符号到字符串的转换。它通过使用符号或字符串作为键来访问值。
hash = HashWithIndifferentAccess.new({:key1 => "value1", :key2 => "value2"})
hash[:key1] # "value1"
hash['key1'] # "value1"

