Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda