哈希键的Ruby值? [英] Ruby value of a hash key?

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

问题描述

我有一个 Ruby 哈希值的列表.有没有办法检查键的值,如果它等于X",那么做Y"?

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"?

我可以使用 hash.has_key? 测试哈希是否有键,但现在我需要知道 if hash.key == "X" then...?

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" }

您可以使用

hash["key1"]

或为

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

或 Ruby 1.9 支持的新格式

or the new format supported in Ruby 1.9

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

您可以使用

hash[:key1]

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

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