I have some legacy code and completely new to Ruby. I want to change the value of a class instance in Ruby.
class CoffeeMachine
attr_reader :water
def initialize
@water = 100
end
end
machine = CoffeeMachine.new
machine.water
I now want to change machine.water to 70. I learned that these instances are protected through something called "Encapsulation". But I'm wondering if there is not any way to change this variable. Following this and this I tried changing it like so:
machine.class_eval {@water = 70}
but it doesn't work. When I print it out like so
puts machine.class_eval '@water' it shows 70 but when I use it in my program it somehow doesn't get stored.
attr_accessor :water?machine.instance_variable_set(:"@water", 70)to set the instance variable's value. Although I'd recommend using theattr_accessoras it gives you both getter and setter methods.waterexplicitly as unchangeable from outside, if you then want to change it? This does not make sense.attr_reader, you only specify that you can read the environment variable. Basically, it generates an accessor method for this variable. Similarily,attr_writercreates a setter method for the variable.attr_accessorcreates both. See here.machine.instance_eval { @water=70 }. Note thatclass_evalwould allow for variables on class scope, whileinstance_eval, as the name implies, can be used for fiddling with instance variables. Of course, you will avoid both if possible, since their use breaks the idea of encapsulation.