random_user_0891
random_user_0891

Reputation: 2071

ruby find value in array of hashes

I have an array of hashes that I need to sort through to find a value. Once the value is found the whole article hash should be returned and not just the one value.

@articles = [{:"xy.id"=>["ID_100"], :"xy.url"=>["http://websiteA.com"], :TestQuestions=>["A//B/C//D, apple"]}, {:"xy.id"=>["ID_200"], :"xy.url"=>["http://websiteB.com"], :TestQuestions=>["E//F/G//H, orange"]}]

what I've tested with so far

# doesn't find the key
@articles.each do |article|
  test_article = article.key?("xy.id")
  puts test_article
end

prints nothing

@articles.each do |article|
  test_article = article.select {|k| k["xy.id"] == "ID_200"}
  puts test_article
end

prints the keys, not sure how to return the entire article hash entry though

@articles.each do |article|
  doc.each do |key, value|
     puts key
  end
end

Upvotes: 0

Views: 566

Answers (1)

Gerry
Gerry

Reputation: 10507

find would do it:

@articles.find { |article| article[:"xy.id"] == ["ID_100"] }
#=> {:"xy.id"=>["ID_100"], :"xy.url"=>["http://websiteA.com"], :TestQuestions=>["A//B/C//D, apple"]}

Things to notice:

  • the key is a symbol, so a : is needed
  • the value is an array, so you need to surround the value with []

Upvotes: 4

Related Questions