【问题标题】:how do I search for a string value inside an array stored in a hash如何在存储在哈希中的数组中搜索字符串值
【发布时间】:2016-10-27 01:25:12
【问题描述】:

我正在使用 ruby​​ on rails 并试图弄清楚我是否可以(和/或如何)在 Array 中搜索特定字符串值的 Hash?如果有匹配项(找到 Bob),我希望它返回 True。

```

string_query = "Bob@gmail.com"

email_array is the following:                                                                                                                       
[
    [0] {
        "email" => "bill@gmail.com",
         "name" => "william"
    },
    [1] {
        "email" => "mike@gmail.com",
         "name" => "michael"
    },
    [2] {
        "email" => "Bob@gmail.com",
         "name" => "robert"
    }
]

```

我在 Stack Overflow 上看到了这个例子——但它是数字的。我的是一个字符串。 How do I get a hash from an array based on a value in the hash?

非常感谢。

【问题讨论】:

  • 如果给定一个散列数组和一个字符串s,是否要返回true,该数组的至少一个元素(散列)的键或值是字符串包含s 作为子字符串?我建议您编辑您的问题以澄清,而不是试图在评论中解释,因为问题应该是清晰和完整的。一件小事:有些读者可能想删减你的代码。为此,他们必须删除[0][1][2]。您应该在发布之前删除这些无关的部分。
  • 另外,请为您的数组分配一个变量(例如,arr = [{ "email"=>...,以便读者无需定义即可引用该变量。

标签: ruby-on-rails arrays ruby hash enumerator


【解决方案1】:

我没有尝试过,因为我现在出去了,但这可以工作

string_query = "Bob@gmail.com"
email_array.each do |s|
   if s['email'] == string_query
       #your comparision statements here 
   end
end

【讨论】:

  • 太好了 - 谢谢。为了使解决方案起作用,我不得不使用 ["email"] ... 双引号。
【解决方案2】:
string_query = "Bob@gmail.com"


email_array = [{
        "email" => "bill@gmail.com",
         "name" => "william"
    },
    {
        "email" => "mike@gmail.com",
         "name" => "michael"
    },
    {
        "email" => "Bob@gmail.com",
         "name" => "robert"
    },
    {
        "email" => "Bob@gmail.com",
         "name" => "robert2"
    }
]

如果你想选择所有匹配的哈希,你可以使用select

email_array.select {|hash| hash["email"] == string_query }

#=> [{"email"=>"Bob@gmail.com", "name"=>"robert"}, {"email"=>"Bob@gmail.com", "name"=>"robert2"}]

如果您只想检查truefalse,请使用any?

email_array.any? {|hash| hash["email"] == string_query }

#=> true

如果您只对第一个实例感兴趣。你可以使用detect

email_array.detect {|hash| hash["email"] == string_query }

#=> {"email"=>"Bob@gmail.com", "name"=>"robert"}

【讨论】:

    【解决方案3】:

    你可以这样做

    email_array.select {|hash| hash["email"] == string_query }.present?
    

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 2017-02-15
      • 2011-01-15
      • 1970-01-01
      • 2010-10-30
      • 2016-06-16
      • 2011-09-02
      • 2015-09-24
      • 2019-10-30
      相关资源
      最近更新 更多