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

74
Visualizações
Ruby/Rails return with result if function call is returning something

Please forgive me if this is something beginner level. I'm looking for a cleaner way of doing something like this,

def function
  return Books.all if Books.any?
  
  return BooksForeign.all if BooksForeign.any?

  nil
end

Since I'm basically duplicating the call, I was wondering if there's a simple and better way of doing this. I just want to return if there's anything returning with Books method or BooksForeign method as the method which expects a return doesn't care if it's Foreign Books or Not.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

def function
  Books.all.presence || BooksForeign.all.presence
end

Object#presence is one of ActiveSupport's more useful core extensions to Ruby. It returns the object if its present? or nil otherwise. Empty collections are not present?.

If you had a whole list of classes you could use Enumerable#find which would return the first non-falsy value:

[Foo, Bar, Baz].find { |klass| klass.all.presence }
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