Dynamically Modify Ruby Instance Variable in Array -


i have array ["moniker", @moniker] moniker can 1 of around 100 instance variables , string representation. want change instance variable located @ index 1 referencing (not data itself, may immutable). doing array[1] = newdata doesn't work because changes whats in array. know simple in c, i'm struggling find way in ruby.

your struggle because thinking c programmer, have access underlying pointers, , mutable. in c, array store pointer mutable integer, , change integer whenever want. in ruby, every variable reference object, and numbers immutable objects. so, @moniker reference object, integer 4. when create array, copy reference array, integer 4 has 2 references: 1 @moniker, , 1 array. have found, changing reference in array not change reference named @moniker--it still refers object 4.

"box" reference in array

this not ruby way of doing things. i'm showing because might illustrate how ruby works references.

you can box reference in array:

@moniker = [4] = ["moniker", @moniker] 

this requires deference array when want access underlying object:

@moniker.first a[1].first 

but can change underlying integer in @moniker , array see change:

@moniker[0] = 42 p a[1].first    # => 42 

encapsulate number in mutable object.

being object oriented language, might encapsulate number in mutable object.

class moniker   attr_accessor :value   def initialize(value)     @value = value   end end 

(attr_accessor :value builds reader , writer methods instance variable @value).

@moniker = moniker.new(4) = ["monikier", @moniker] @moniker.value = 42 p a[1].value    # => 42 

you chose better name "value." couldn't because don't know value represents.

why these 2 solutions work

this comment jörg w mittag, deserves part of answer:

it may seem obvious, wanted mention explicitly: 2 solutions same solution. first uses existing class generic semantics, the second defines new class precise semantics specific encapsulated value. in both cases, it's wrapping immutable value in mutable value , mutating "outer" value.


Comments