Home > Software design >  Getting values out of a nested array of hashes
Getting values out of a nested array of hashes

Time:09-10

I am working on question for the Odin project. I have to run tests on the answers I give, and am not able to pass a test by using the code I have made. I got an unexpected result of the correct hash, but it is enclosed inside of an array for some reason.

def find_favorite(array_of_hash_objects)
  # take an array_of_hash_objects and return the hash which has the key/value
  # pair :is_my_favorite? => true. If no hash returns the value true to the key
  # :is_my_favorite? it should return nil
 
  
  # array_of_hash_objects will look something like this: # [
  #   { name: 'Ruby', is_my_favorite?: true },
  #   { name: 'JavaScript', is_my_favorite?: false },
  #   { name: 'HTML', is_my_favorite?: false }
  # ]

  # TIP: there will only be a maximum of one hash in the array that will
  # return true to the :is_my_favorite? key
end

My solution:

array_of_hash_objects.select {|key, value| key[:is_my_favorite?] == true}

I received this after running test:

`Failure/Error: expect(find_favorite(array)).to eq(expected_output)

   expected: {:is_my_favorite?=>true, :name=>"Ruby"}
        got: [{:is_my_favorite?=>true, :name=>"Ruby"}]`

My question is, how do I get the returned value out of an array? I predict I might be using the wrong method, but I think it might help to get an explanation from someone who sees the problem. No googling is solving this. This is my first stack overflow question.

CodePudding user response:

change from select to find. simply, the semantic of the methods is different:

  • select returns all the elements that match the condition, so a collection, even if it's of length one or zero
  • find returns the first element which match the condition or nil if none matches

in your case, you want find

  •  Tags:  
  • ruby
  • Related