Search code examples
rubyinstance

how to change instance variables in class in ruby


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.


Solution

  • In your Scenario this will be more convenient way to Handle it

    class CoffeeMachine
      attr_reader :water
      def initialize(water=100)
        @water = water
      end
    end
    
    machine = CoffeeMachine.new
    
    machine.water # 100
    
    machine = CoffeeMachine.new(70)
    
    machine.water # 70