After execute the block , it looks like that ruby destroied the former
‘x’ object, the ‘x’ object has object_id 4 now, which is same as
a[4].object_id.
If so , does it mean that I must choose another variable name in
array’s each block to keep the ‘x’ object alive ?
After execute the block , it looks like that ruby destroied the former
‘x’ object, the ‘x’ object has object_id 4 now, which is same as
a[4].object_id.
Yes, if you do {|foo|…} and you have a local variable foo outside the
block,
then the outer foo will be replaced by the value that is yielded to the
block.
This is a property of blocks in 1.8, not of each in particular. This
behaviour
will no longer be present in 1.9.
If so , does it mean that I must choose another variable name in
array’s each block to keep the ‘x’ object alive ?
After execute the block , it looks like that ruby destroied the former
‘x’ object, the ‘x’ object has object_id 4 now, which is same as
a[4].object_id.
After execute the block , it looks like that ruby destroied the former
‘x’ object,
There is no object destroyed. The variable x is made to point to
another object. If there are no more references to the object pointed
to by x before it can be garbage collected at any point in time after x
has been made to point to another instance.
Yes.
Just to throw in the keyword for the concept involved to help in further
research of the matter: the concept is called “scoping” - the scoping
rules for a programming language determine which variables are visible
in which program artifacts (blocks, methods…) and especially what
happens to variables with identical names.
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.