jessicaraygun
jessicaraygun

Reputation: 315

Ruby temporary variable assignment and modification

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?

Upvotes: 1

Views: 1313

Answers (1)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

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

Upvotes: 2

Related Questions