Reputation: 107
require 'csv'
class Apple
def initialize()
@num = CSV.read("Location", :headers=>false)
#assume @num[0][0] has 'A1D'
end
def Display()
puts @num[0][0]
end
def Problem()
temp = @num[0][0]
temp['D'] = "A"
end
end
ap = Apple.new
ap.Display
ap.Problem
ap.Display
Displayed answer A1D A1A
When you assign temp to @num[0][0], I don't want any changes happening in @num when I make changes in temp value.
I am not sure how to do this. Please help.
Upvotes: 0
Views: 30
Reputation: 237060
If you don't want to mutate the original object, you need to make a copy (say, by dup
). Remember, though, that any instance variables in the dup'ed object will still reference the same objects they did in the original, so you'll need to dup those as well if you want to modify them.
Upvotes: 1
Reputation: 118271
You need to use just temp = @num[0][0].dup
. As you did temp = @num[0][0]
, thus temp
is pointing to the object, which is @num[0][0]
giving. Thus any change to the string object pointed by temp
will affect the string lies in @num[0][0]
.
Upvotes: 2