ruby - Why does a variable that gets assigned inside a Proc not persist over repeated calls of the Proc? -
ruby 1.9.2 code:
def append_string_to_text(string_to_append) string_to_alter = 'starting_bit' p "outside block: string_to_alter.object_id #{string_to_alter.object_id}" proc.new p "****** start of block: string_to_alter.object_id #{string_to_alter.object_id}" p "defined?(new_string_created_in_block) #{defined?(new_string_created_in_block) == true}" unless defined?(new_string_created_in_block) p "new_string_created_in_block undefined. lets define it." new_string_created_in_block = 'test' end p "new_string_created_in_block.object_id #{new_string_created_in_block.object_id}" string_to_alter = string_to_alter + string_to_append p "end of block: string_to_alter.object_id #{string_to_alter.object_id}" string_to_alter end end proc = append_string_to_text('_text_at_the_end') p proc.call p proc.call
output:
"outside block: string_to_alter.object_id 70283335840820" "****** start of block: string_to_alter.object_id 70283335840820" "defined?(new_string_created_in_block) false" "new_string_created_in_block undefined. lets define it." "new_string_created_in_block.object_id 70283335840520" "end of block: string_to_alter.object_id 70283335840440" "starting_bit_text_at_the_end" "****** start of block: string_to_alter.object_id 70283335840440" "defined?(new_string_created_in_block) false" "new_string_created_in_block undefined. lets define it." "new_string_created_in_block.object_id 70283335840180" "end of block: string_to_alter.object_id 70283335840100" "starting_bit_text_at_the_end_text_at_the_end"
the first time block run, string_to_alter
variable points object created @ start of append_string_to_text
method, because block closure. block creates new variable new_string_created_in_block
, , creates new block local variable string_to_alter
, shadowing outer variable string_to_alter
.
the second time block run, string_to_alter
variable points object created during first time block run.
why during second run, new_string_created_in_block
undefined? gets assigned during first run, , assigning of string_to_alter
variable gets persisted first run, why doesn't new_string_created_in_block
persist well?
string_to_alter
gets persisted because it's outside of proc
block , part of closure. proc
block gets instantiated @ each invocation, however, hence lack of persistence of of variables defined within block.
Comments
Post a Comment