散列键的Ruby值? [英] Ruby value of a hash key?

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

问题描述

我有一个Ruby哈希值的列表。有没有办法来检查键的值,如果它等于X,然后做Y?

我可以测试,看看哈希是否有一个键使用 hash.has_key?,但现在我需要知道如果hash.key ==X,那么... 所以如果你的哈希类似于

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

您可以通过

  hash [key1] 

或for

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

或Ruby 1.9支持的新格式

  hash = {key1:value1,key2:value2} 

你可以通过

  hash [:key1] 


I've got a list of values that are in a Ruby hash. Is there a way to check the value of the key and if it equals "X", then do "Y"?

I can test to see if the hash has a key using hash.has_key?, but now I need to know if hash.key == "X" then...?

解决方案

Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol. So if your hash is similar to

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

you can access the value with

hash["key1"]

or for

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

or the new format supported in Ruby 1.9

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

you can access the value with

hash[:key1]

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

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