In this session we covered Classes, Modules and Mixins in more depth. Ruby's inheritance mechanism was covered, as well as the uses of instance and class variables.
5. Classes
• Classes are the blueprints of Objects
• Classes define the way an Object keeps
state, what it’s value is
• Classes define the way an Object behaves,
what methods it provides
6. Classes & Attributes
class BookInStock
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
end
7. Classes & Attributes
book = BookInStock.new(“1234”, 3.00)
p book
#<BookInStock:... @isbn=”1234”, @price=3.00>
8. Classes & Attributes
class BookInStock
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
def to_s
“ISBN: #{@isbn}, price: #{@price}”
end
end
18. Access Control
• Public methods (the default) can be called by
anyone in any context
• Protected methods can only be called by the
Class that defines them or its Subclasses
• Private methods can only be called by the
within the Class that defines them
24. Modules
module Trig
PI = 3.141592654
def Trig.sin(x)
#...
end
def Trig.cos(x)
#...
end
end
y = Trig.sin(Trig::PI/4)
25. Mixins
• Mixins overcome the limitations of single-
inheritance
• Mixins allow behavior to be added to a class
within requiring inheritance
26. Mixins
module OnSale
def on_sale?
true
end
end
class BookOnSale < BookInStock
include OnSale
end
b = BookOnSale.new(“12340”, 1.00)
puts “Price $#{b.price}!” unless b.on_sale?
puts “ONLY $#{b.price}!” if b.on_sale?
ONLY $1.00!
28. For Next Week
For the New to Programming
• Read Chapters 9, 10, 11, 12 & 13 in LtP
• Complete exercises for each chapter
For Everyone
• Read Chapter 3, 4, 5 & 6 in PR1.9
• Work through Ruby Koans: about_classes,
about_open_classes, about_inheritance,
about_modules