Classes
class Dog
attr_reader :name
def initialize(name)
@name = name
@tricks = []
end
def learn(trick)
@tricks << trick
end
def to_s
"#{@name} knows #{@tricks.size} tricks"
end
end
rex = Dog.new("Rex")
rex.learn("sit")
puts rex # Rex knows 1 tricks
puts rex.name # Rex
initializeruns when you callDog.new(...).- Variables starting with
@are instance variables: each dog has its own. - Instance variables are private.
attr_reader :namecreates a method to read@name;attr_accessorcreates read and write methods. to_sis whatputsand interpolation use.
Errors
raise signals a problem; begin ... rescue handles it:
raise ArgumentError, "Amount must be positive" if amount <= 0
Inheritance
class GuideDog < Dog
def guide = "#{name} is guiding" # a one-line method
end
GuideDog gets everything Dog has. super calls the parent's version of the current method.
Your task
class Account:Account.new(owner)starts with a balance of 0; readers forownerandbalance;deposit(amount);withdraw(amount)raisingArgumentErrorif there is not enough money;to_sgiving"Chipo: $25".class SavingsAccount < Accountwithadd_interest(rate), which depositsbalance * rate.