如何在存储在哈希中的数组中搜索字符串值

时间:2016-10-27 01:25:12

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

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

```


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

Console.WriteLine("First Name: ");
Console.WriteLine("Last Name: ");
Console.WriteLine("Badge Number: ");
Console.SetCursorPosition(12, 0);
string fname = Console.ReadLine();
Console.SetCursorPosition(11, 1);
string lname = Console.ReadLine();
Console.SetCursorPosition(14, 2);
string badge = Console.ReadLine();

```

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

非常感谢。

3 个答案:

答案 0 :(得分:1)

我现在没有尝试这个,但这可以工作

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

你可以这样做

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