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

264
Vistas
Why am I accidentally creating palindromes in Ruby?

I am using Ruby to take in a string and reverse the order of the letters (so that the last letter becomes the first, etc.)

When I use the below code, I accidentally create a palindrome by taking half of the string and repeating it:

 def reverse(word)

  i = 0
  new_word = word
  
  while i < word.length
    
   new_word [i] = word [word.length - i - 1]
    
    i += 1 
  
  end
  
 return new_word
  
end

puts reverse("cat")          # => "tac"
puts reverse("programming")  # => "gnimmargorp"
puts reverse("bootcamp")     # => "pmactoob"

However, when I use the below code, I get it right:

 def reverse(word)

  i = 0
  new_word = ""
  
  while i < word.length
    
   new_word [i] = word [word.length - i - 1]
    
    i += 1 
  
  end
  
 return new_word
  
end

puts reverse("cat")          # => "tac"
puts reverse("programming")  # => "gnimmargorp"
puts reverse("bootcamp")     # => "pmactoob"

I just changed word to "" (line 4) and it works. Why?

My suspicion is that the string (word) itself is changing with each iteration, but it isn't supposed to do that is it?

Thank you all.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

My suspicion is that the string (word) itself is changing with each iteration, but it isn't supposed to do that is it?

Your suspicion is spot-on.

new_word = word

This does not create a new string. It tells new_word to refer to the same list as word. Ruby is one of a handful of languages where strings are actually mutable objects. So when you modify new_word with []=, you're also modifying word. As you've already noticed, you can start with an empty string

new_word = ""

Alternatively, if you want to start with word and modify it (there are certainly some algorithms where doing so can be beneficial), we can use the #dup method, which performs a shallow copy of the data

new_word = word.dup

You can check whether two variables refer to the exact same object (as opposed to simply looking the same) using #equal?

puts(new_word.equal? word)
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