如何在存储在散列中的数组中搜索字符串值
how do I search for a string value inside an array stored in a hash
我在 rails 上使用 ruby 并试图弄清楚我是否可以(and/or 我如何)在数组中搜索特定字符串值的哈希?如果有匹配项(找到 Bob),我希望它 return 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?
非常感谢。
我还没试过这个,因为我现在出去了,但这可行
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"
}
]
如果你想要 select 所有匹配的哈希,你可以使用 select
email_array.select {|hash| hash["email"] == string_query }
#=> [{"email"=>"Bob@gmail.com", "name"=>"robert"}, {"email"=>"Bob@gmail.com", "name"=>"robert2"}]
如果您只想检查 true
或 false
,请使用 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"}
你可以这样做
email_array.select {|hash| hash["email"] == string_query }.present?
我在 rails 上使用 ruby 并试图弄清楚我是否可以(and/or 我如何)在数组中搜索特定字符串值的哈希?如果有匹配项(找到 Bob),我希望它 return 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?
非常感谢。
我还没试过这个,因为我现在出去了,但这可行
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"
}
]
如果你想要 select 所有匹配的哈希,你可以使用 select
email_array.select {|hash| hash["email"] == string_query }
#=> [{"email"=>"Bob@gmail.com", "name"=>"robert"}, {"email"=>"Bob@gmail.com", "name"=>"robert2"}]
如果您只想检查 true
或 false
,请使用 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"}
你可以这样做
email_array.select {|hash| hash["email"] == string_query }.present?