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