Reputation: 6259
Here I have a little demo-code:
class UpdateHash
def initialize(value)
@value = value
save
end
def save
@value = 10
end
end
hash = {uno: "50"}
UpdateHash.new(hash[:uno])
puts hash[:uno]
=> "50"
What would I have to change so that the result of puts hash[:uno]
is not "50"
but 10
. Is there the possibility to update the value of the hash in the class, without having to pass the whole Hash?
This would work: UpdateHash.new(hash)
. But am I able to only pass the value and update the value in the class?
Upvotes: 0
Views: 796
Reputation: 55758
When passing objects around as arguments to methods, what happens is that Ruby copies the reference to the object. This is often called pass-by-object-reference which in turn is a variant of a pass-by-value system.
What this means is that while you can mutate the object pointed to by the passed reference or even update the reference to a point to a new object (i.e. setting a new object to the existing variable), you can't force other references to the same object point to a different object.
As such, on order to update the hash and set a new value, you need a reference to the hash itself. Just setting a new value to the @value
variable won't update any other references like the one inside the hash.
Now, if the value would have been e.g. an Array
you could have mutated it inside your class by e.g. adding new elements in your save method which would then be reflected in the hash too. This is possible since the reference to the object (i.e. the array in this case) is not changed here.
Upvotes: 3
Reputation: 211570
You'll need to capture a reference to the parent object if you want to manipulate any of the values and have them back-propagate to the caller's level:
class UpdateHash
def initialize(hash)
@hash = hash
save
end
def save
@hash[:uno] = 10
end
end
hash = {uno: "50"}
UpdateHash.new(hash)
puts hash[:uno]
# => 10
Upvotes: 1
Reputation: 9497
Something like this perhaps:
class UpdateHash
def initialize(hash,key)
hash[key] = save
end
def save
10
end
end
hash = {uno: "50"}
UpdateHash.new(hash,:uno)
puts hash[:uno] #=> 10
Upvotes: 1