Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I accidentally creating palindromes in Ruby?

Tags:

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.

like image 503
marwanelesk Avatar asked Nov 19 '25 06:11

marwanelesk


1 Answers

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)
like image 139
Silvio Mayolo Avatar answered Nov 22 '25 00:11

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!