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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -