ruby - Change values of variables in array -
i have array made variables, , want perform same operation on each, , store result in original variable:
(one, two, three) = [1, 2, 3] [one, two, three].map!{|e| e += 1} # => [2, 3, 4] # but: [one, two, three] # => [1, 2, 3] # have to: (one, two, three) = [one, two, three].map{|e| e += 1} # => [2, 3, 4] [one, two, three] # => [2, 3, 4]
this doesn't seem "right way" it, i'm not managing find "right way". have vague ideas what's going on, i'm not sure, explanation appreciated.
my actual use case i've got named parameters , i'm e = file.new(e) if e.is_a? string
numbers (such fixnum
) in ruby immutable. cannot change underlying value.
once assign one = 1
, not possible change value of one
without new assignment. when one += 1
. assigning new value 2
variable one
; it's whole new object.
you can see more looking @ object_id
(a.k.a. __id__
):
one = 1 1.object_id # => 2 one.object_id # => 2 1 += 1 one.object_id # => 5 2.object_id # => 5
now in array#map!
statement, you're not changing one
object. reference object stored in array; not actual variable. when enumerate map!
, object returned block stored in internal reference location @ same position. think of first pass on map!
similar following:
one = 1 one.object_id # => 2 arr = [one] arr[0].object_id # => 2 arr[0] += 1 # re-setting object @ index 0 # not changing original `one`'s value arr[0] # => 2 arr[0].object_id # => 5 1 # => 1 one.object_id # => 2
since these fixnum
objects immutable, there no way change value. why have de-reference result of map
original values:
(one, two, three) = [1, 2, 3] one.object_id # => 3 two.object_id # => 5 three.object_id # => 7 (one, two, three) = [one, two, three].map{|e| e += 1} one.object_id # => 5 two.object_id # => 7 three.object_id # => 9
Comments
Post a Comment