Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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"}]
 
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!