ruby hash 检查值是否存在

标签 ruby hash

一定是个简单的问题..但我似乎找不到答案。 我正在尝试检查哈希中特定键的值是否存在。

hash = {{"name" => "John", "Loc" => "US", "fname" => "John Doe"},
        {"name" => "Eve", "Loc" => "UK", "fname" => "John Eve"}}

目前我正在遍历哈希,以检查 if h["name"] = "John"...

我正在寻找 .include.has_value? 类型的方法是否可用。我阅读了有关哈希的文档和手头上的一本书,但找不到它。

我认为像 if hash["name"].has_value?("John") 这样的东西比遍历哈希最有用。在此先感谢您的帮助!

最佳答案

首先,我们的散列不是有效的散列。我想你想要一个像这样的哈希数组

array = [
  { "name" => "John", "Loc" => "US", "fname" => "John Doe" },
  { "name" => "Eve",  "Loc" => "UK", "fname" => "John Eve" }
]

然后你可以这样做:

array.select { |hash| hash['name'] == 'John' }
# => returns [{"name" => "John", "Loc" => "US", "fname" => "John Doe"}] 

array.any? { |hash| hash['name'] == 'John' }
# => true

关于ruby hash 检查值是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25706697/

相关文章:

c++ - unordered_map 的用户定义哈希函数

ruby - 用大写单词替换单词

ruby - 如何设置 ruby​​ murmur 哈希的种子值

ruby - 隐藏系统命令导致 ruby

c++ - Unordered_map 使用指针地址作为键

c++ - Unordered_Map of Maps 还是 Priority_Queues?

ruby - 哪种redis数据类型适合存储用户?

ruby-on-rails - 使用包含/连接

arrays - 如何在散列中插入散列的散列?

ruby - Ruby 中的哈希值存储为副本?