Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

248
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda