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

242
Visualizações
Why does this method return three values?

I have following Ruby programm:

def swap (a,b)
   return a,b = b,a
end

puts swap(5,3)

I expected the output.

3
5

But I get.

5
3
5

What's the reason?

Thanks!

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

0

Why does this method return three values?

It's because of the return statement, Ruby tries to interpret the right-hand side as an array and your code:

return a,b = b,a

gets evaluated as: (parentheses added for clarity)

return [a, (b=b), a]

i.e. a 3-element array [a, b, a] (assigning b to itself does nothing)

over 4 years ago · Santiago Trujillo Relatório

0

Remove the keyword return. It is actually doing: return a, (b), a. Where (b = b)

def swap(a,b)
  a, b = b, a
end

puts swap(5,3)

Output

=> 3, 5
over 4 years ago · Santiago Trujillo Relatório

0

In your program: in swap function the return you have given is return a,b = b,a remove a,band diretcly write return b,a. you will get your expected output. Reason: in return a,b = b,a is return first the value of a then executing b=b,a. Hope this might help you out

def swap (a,b)
   return b,a
end

puts swap(5,3)

Output

3
5
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