Defining Methods within a Class : Member method « Class « Ruby






Defining Methods within a Class



class Account
  attr_reader :name, :balance

  def initialize(n, b)
    @name = n
    @balance = b
  end

  def add_interest(rate)
    @balance += @balance * rate / 100
  end

  def display
    printf("%s, you have $%5.2f in your account.\n",
            @name, @balance)
  end
end

my_account = Account.new("Barry", 10.00)
my_account.add_interest(5.0)
my_account.display

your_account = Account.new("Harriet", 100.00)
your_account.add_interest(7.0)
your_account.display

 








Related examples in the same category

1.Define a method to retrieve the value.
2.a simple demonstration of a class with two methods
3.implement an each method, and get these methods for "free":
4.Compare method
5.Add method to a variable only