[英]how do I search for a string value inside an array stored in a hash
I am using ruby on rails and trying to figure out if I can (and/or how I) search for a Hash within an Array for a specific string value? 我在轨道上使用ruby,试图找出是否可以(和/或如何)在数组中搜索特定字符串值的哈希值? If there is a match (finds Bob), I want it to return True. 如果有匹配项(找到鲍勃),我希望它返回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"
}
]
``` ```
I see this example on Stack Overflow - but it is numeric. 我在堆栈溢出中看到了此示例-但它是数字。 Mine is a string. 我的是绳子。 How do I get a hash from an array based on a value in the hash? 如何基于哈希值从数组中获取哈希?
Many thanks. 非常感谢。
I have not tried this as I am out now, but this could work 我现在不在,还没有尝试过,但是可以用
string_query = "Bob@gmail.com"
email_array.each do |s|
if s['email'] == string_query
#your comparision statements here
end
end
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"
}
]
If you want to select all of the matching hashes you can use select
如果要选择所有匹配的哈希,可以使用select
email_array.select {|hash| hash["email"] == string_query }
#=> [{"email"=>"Bob@gmail.com", "name"=>"robert"}, {"email"=>"Bob@gmail.com", "name"=>"robert2"}]
If you simply want to check for true
or false
, use any?
如果您只想检查true
或false
,请使用其中的any?
email_array.any? {|hash| hash["email"] == string_query }
#=> true
If you are only interested in the first instance. 如果您只对第一实例感兴趣。 You can use detect
您可以使用detect
email_array.detect {|hash| hash["email"] == string_query }
#=> {"email"=>"Bob@gmail.com", "name"=>"robert"}
你可以这样做
email_array.select {|hash| hash["email"] == string_query }.present?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.