Classes – creating your own things
In Ruby, everything is an object. With a class you build objects of your own. A class is like a blueprint: it describes what its objects know and can do. With new you build an object from the blueprint – as many as you like:
class Cat
attr_reader :name
def initialize(name)
@name = name
end
def shout
"Meow!"
end
end
k = Cat.new("Mimi")
k.shoutinitialize runs on Cat.new. Variables with @ are called instance variables and belong to the object, and attr_reader :name makes @name readable from outside – try k.name! And another aha: attr_reader :name is no special keyword but a perfectly normal method call without parentheses – as learned in lesson 22: attr_reader(:name).
Every object has instance variables of its own. Two cats from the same blueprint know nothing about each other:
mimi = Cat.new("Mimi")
felix = Cat.new("Felix")
[mimi.name, felix.name, felix.shout]attr_reader makes a value readable only. If it should be changeable from outside too, use attr_accessor – reading and writing. A class's methods may read and change the instance variables; that's how every object remembers its state. And a method called to_s decides how the object looks as text – puts and interpolation ask for it:
class Hamster
attr_accessor :name
attr_reader :hunger
def initialize(name)
@name = name
@hunger = 5
end
def feed(seeds)
@hunger = [@hunger - seeds, 0].max
end
def to_s
"#{@name} (hunger: #{@hunger})"
end
end
nibbles = Hamster.new("Nibbles")
nibbles.feed(2)
puts nibbles
nibbles.name = "Nibbles the Great"
puts "New name: #{nibbles}"Go on feeding Nibbles: nibbles.feed(10) – the hunger never drops below 0, max takes care of that. Without to_s, by the way, puts would only print something like #<Hamster:0x000…> – how should Ruby know how to describe a hamster?
Numbers and strings are objects of classes, too. And even every class is an object itself – one of the class Class:
[5.class, "bacon".class, nibbles.class, Hamster.class]Two cats with the same name are still two objects. Each has its own @name:
mimi = Cat.new("Mimi")
also_mimi = mimi # the same cat
twin = Cat.new("Mimi") # another cat, same name
show_objects(mimi: mimi, also_mimi: also_mimi, twin: twin)mimi.equal?(also_mimi) is true, mimi.equal?(twin) is false: one arrow target or two. equal? asks whether it is the same object.
Fox: with initialize(name), attr_reader :name and a method shout that returns "Chunky Bacon!".# class Fox
# ...
# end
PiggyBank starts empty, add(cents) puts coins in, and total says how much is inside. After add(50) and add(20), total should give 70. The instance variable needs its starting value in initialize.# class PiggyBank
# ... # starts empty; add(cents) puts coins in; total answers how much is in
# end
# bank = PiggyBank.new
# bank.add(50)
# bank.add(20)
# bank.total