If it has the same object_id, why changing a value in a method doesn't affect the caller in Ruby? -
i have method:
def change_value(obj) puts obj.object_id #70275832194460 obj = nil puts obj.object_id #8 end obj = "hi there" puts obj.object_id #70275832194460 change_value(obj) puts obj.object_id #70275832194460 puts obj #still 'hi there', while expect nil.
why if passing object, , changing value new value doesn't maintained outside of method?
your method named badly. named change_value
, doesn't change value, changes reference. , since ruby pass-by-value, not pass-by-reference, changing reference won't caller. if did change value, able observe difference:
def change_value(obj) puts obj.object_id #70275832194460 obj.replace('hi back!') puts obj.object_id #70275832194460 obj = nil puts obj.object_id #8 end obj = 'hi there' puts obj.object_id #70275832194460 change_value(obj) puts obj.object_id #70275832194460 puts obj # 'hi back!'
Comments
Post a Comment