Search code examples
rubyinstance-variables

How do I make my class attribute not be able to access instance variable directly?


How can I make my code work so that the balance attribute doesn't access the instance variable(I believe it's @balance) directly? Can someone explain what it means for an attribute to access an instance variable?

I'm new to using Ruby and just got into learning about Ruby classes. In this chapter, my objectives is to understand the concept of instance variables, demonstrate the us of getter and setter methods, understand how to use instance methods, and understand the concept of encapsulation.

class BankAccount
  attr_accessor :balance

  def initialize(balance)
    @balance = balance
  end

  def withdraw(amount)
    if (balance >= amount)
      @balance = balance - amount
    end
  end
end

Solution

  • In Ruby attr_reader :balance is more or less just a convenience version of the following method:

    def balance
      @balance
    end
    

    Similarly, attr_writer :balance is just a short form for

    def balance=(value)
      @balance = value
    end
    

    And attr_accessor :balance is short for attr_reader :balance plus attr_writer :balance.

    So as you can see attr_reader accessing the instance variable is nothing special, e.g. in your code you also access the instance variable in #initalize and #withdraw.

    You need to clarify why you wouldn't want to access it directly. And what that even means. Because you can either access the instance variable using @balance or not, there is no indirect in my opinion.