theClawistheLaw
theClawistheLaw

Reputation: 17

Returning nil when unable to locate value of true in an array of hashes

I need to be able to return nil when I can't find is_my_favorite? to have a value of true, and return the hash that is the favorite. My current code will return the hash that is true, but if they were all false for example, I want to return nil, but I can't come up with a way of doing so without breaking my code, which currently does half of what I want.

# 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 }
  # ]
  array_of_hash_objects.each do |item|
    item.each do |words|
      if words.one?(true)
        return item
    
        
      end
    end
  end
end

I've tried this:

  array_of_hash_objects.each do |item|
    item.each do |words|
      if words.one?(true)
        return item
      else
        return nil
    
        
      end
    end
  end
end

but this returns

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

   expected: nil
        got: [{:is_my_favorite?=>false, :name=>"Python"}, {:is_my_favorite?=>false, :name=>"JavaScript"}, {:is_my_favorite?=>false, :name=>"HTML"}]
 

Upvotes: 1

Views: 162

Answers (1)

kkp
kkp

Reputation: 446

You could simply use the find method https://apidock.com/ruby/Enumerable/find

array_of_hash_objects = [
  { name: 'Ruby', is_my_favorite?: true },
  { name: 'JavaScript', is_my_favorite?: false },
  { name: 'HTML', is_my_favorite?: false }
]

array_of_hash_objects.find { |item| item[:is_my_favorite?] }

This will give you:

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

Now if you got an array with all false values in the hash:

array_of_hash_objects = [
  { name: 'Ruby', is_my_favorite?: false },
  { name: 'JavaScript', is_my_favorite?: false },
  { name: 'HTML', is_my_favorite?: false }
]
array_of_hash_objects.find { |item| item[:is_my_favorite?] }

You will get:

=> nil

Upvotes: 3

Related Questions