1

I have a word like "hat", and I want to make a new word that is exactly the same, but with a different last letter.

word = "hat"
temp = word
temp[temp.length-1] = "d"

puts "temp is #{temp}"
puts "word is #{word}"

# Output:
# temp is had
# word is had

I would now expect temp = "had" and word = "hat" but both of the words get changed to had!

I have a hunch that this might have to do with both variables pointing to the same location in memory?

Why is this happening, and how can I keep both values?

jessicaraygun
  • 315
  • 1
  • 4
  • 15
  • You can also use [String#sub](http://ruby-doc.org/core-2.2.0/String.html#method-i-sub) with a regular expression: `'hat'.sub(/.$/,'d') #=> 'had'`. This does not alter `"hat"`. – Cary Swoveland Mar 17 '15 at 23:16

1 Answers1

2

Why is this happening

You should definitely read this Is Ruby pass by reference or by value?

how can I keep both values?

use dup. it copies the object

word = "hat"
temp = word.dup
temp[temp.length-1] = "d"

puts "temp is #{temp}"
puts "word is #{word}"

# Output:
# temp is had
# word is hat
Community
  • 1
  • 1
Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41