Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!