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

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

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 Denunciar

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 Denunciar

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