В вашей первой ситуации все, что вы сделали, это изменили, на какой объект arr
указывает - вы на самом деле не изменили оригинал. Это можно доказать с помощью следующего скрипта:
# Given our test value...
test_array = [1, 2]
# we can verify the values and the object_ids
puts "Value of `test_array`: #{test_array.inspect}"
puts "Object_id of `test_array`: #{test_array.object_id}"
# now, let's put it in a container and run it through a block
@array_container = [test_array]
@array_container.each do |arr|
# Just to prove that `arr` points at test_array
puts "Object_id of `arr`: #{arr.object_id}"
# and that it's the same as the first element in our container
puts "@container.first.object_id: #{@array_container.first.object_id}"
# but, when we re-assign our block variable
arr = [3, 4]
# we get different values
puts "Object_id of `arr`: #{arr.object_id}"
puts "@container.first.object_id: #{@array_container.first.object_id}"
end
Какие выходы ...
Value of `test_array`: [1, 2]
Object_id of `test_array` : 2150710260
Object_id of `arr` : 2150710260
@container.first.object_id: 2150710260
Object_id of `arr` : 2150708040
@container.first.object_id: 2150710260
Так чем же это отличается в случае 2? В случае 2 вы фактически вызываете саморазрушающий метод, который внесет изменения в исходный объект, на который ссылается arr