Ruby - 获取散列值 [英] Ruby - getting value of hash

查看:130
本文介绍了Ruby - 获取散列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个散列,像

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



我有一个变量 k 作为'key1''key2'



我想将 k 的值存入变量 v



如果或 case 没有任何方法可以使用来实现这一点。单线解决方案是首选。

解决方案

将密钥从字符串转换为符号,然后在哈希中查找。

  hash = {:key1 => value1,:key2 => value2} 
k ='key1'

hash [k.to_sym]#或者iow,hash [:key1],它将返回value1

Rails使用这个名为 HashWithIndifferentAccess ,这在这种情况下证明是非常有用的。我知道你只用Ruby标记了你的问题,但你可以从Rails的源代码中窃取这个类的实现,以避免字符串到符号和符号在你的代码库中字符串转换。它使得该值可以通过使用符号或字符串作为键来访问。

  hash = HashWithIndifferentAccess.new({:key1 = >value1,:key2 =>value2})
hash [:key1]#value1
hash ['key1']#value1


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.

解决方案

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"

这篇关于Ruby - 获取散列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆