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

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

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