2

Given this array:

[[{"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[]}],
[{"RepCode"=>"ABNX", "ID"=>"637e9117-ed03-45ef-8950-a7220087ee9a", "Name"=>"Eckerson, Kathy", "Folios" => [{"ID"=>"d0cda2be-c142-47d1-9a81-a76c0eea2765"}],
[{"RepCode"=>"ABCD", "ID"=>"637e9117-ed03-45ef-8950-a234902038", "Name"=>"Sarah, Barber", "Folios" => [{"ID"=>"46aafe31-f686-49e2-9d58-c694ea55c14f"}]]

I need to return the ONE array that matches the given id for the Folio key

CODE:

correct_manager = managers.detect do |manager|
  manager.first["Folios"].map { |f| f["ID"] == "d0cda2be-c142-47d1-9a81-a76c0eea2765" }
end

That returns:

{"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[]}

And I want it to return

{"RepCode"=>"ABNX", "ID"=>"637e9117-ed03-45ef-8950-a7220087ee9a", "Name"=>"Eckerson, Kathy", "Folios" => [{"ID"=>"d0cda2be-c142-47d1-9a81-a76c0eea2765"}

because the ID's match in the detect method.

How can I return the one array that matches the passed in id?

2
  • 2
    Your array seems to be bad formatted. Commented Mar 30, 2018 at 21:46
  • Do the Folios arrays ever contain more than one Folio? Commented Mar 30, 2018 at 22:03

3 Answers 3

2

You can use Enumerable #find

correct_manager = managers.find do |manager|
  folios = manager.first["Folios"][0] || {}
  folios["ID"] == "d0cda2be-c142-47d1-9a81-a76c0eea2765"
end
Sign up to request clarification or add additional context in comments.

Comments

1

First let's format your data correctly:

managers =  [
  [ {"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[] } ],
  [ {"RepCode"=>"ABNX", "ID"=>"637e9117-ed03-45ef-8950-a7220087ee9a", "Name"=>"Eckerson, Kathy", "Folios" => [{"ID"=>"d0cda2be-c142-47d1-9a81-a76c0eea2765"}] } ],
  [ {"RepCode"=>"ABCD", "ID"=>"637e9117-ed03-45ef-8950-a234902038", "Name"=>"Sarah, Barber", "Folios" => [{"ID"=>"46aafe31-f686-49e2-9d58-c694ea55c14f"}] } ] 
]

target_id = 'd0cda2be-c142-47d1-9a81-a76c0eea2765'

managers.flatten.find{|k,_v| k['Folios'].any?{|f| f.key?('ID') && f['ID'] == target_id}}

Comments

1
def doit(managers, val)
  managers.find { |(h)| h["Folios"] == ["ID"=>val] }
end

managers = [
  [{ "RepCode"=>"AL20", "Folios"=>[] }],
  [{ "RepCode"=>"ABNX", "Folios"=>[{ "ID"=>"d0cda2be-c142-47d1-9a81" }] }],
  [{ "RepCode"=>"ABCD", "Folios"=>[{ "ID"=>"46aafe31-f686-49e2-9d58" }] }]
]

doit(managers, "d0cda2be-c142-47d1-9a81")
  # => [{"RepCode"=>"ABNX", "Folios"=>[{"ID"=>"d0cda2be-c142-47d1-9a81"}]}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.