3. Class Features
All instance variables are private by default
No need to declare instance variables
Class is mutable
Method is though sending message
Initialize is private method
4. Class is mutable
Change the method length of String
class String
def length
0
end
end
a = "I am a very long string"
a.length # => 0
6. Class Example
class Book
def initialize(isbn, price)
@isbn = isbn
@price = price
end
end
book = Book.new("a book",100)
parameter from new
@xx are instance variable
12. Module Feature
Group variables , classes, methods
Act as namespace (~sandbox)
Cannot have instance, but have instance
method
Can have module method, module.method
Access content by ::
14. Mixin
Another way to increase functionality of the
class
Include the module in the class
Instance methods will be included in the
class
Like “mix” in the class
17. True power of mixin
Give you a lot of functionality
But you only have to implement one or two
methods
Great flexibility
Eg. Comparable, you have to implement
<=>(other) in order to gain the ability to be
compared
20. Comparable (cont’d)
p1 = Person.new("Matz")
p2 = Person.new("Guido")
p3 = Person.new("Larry")
# Compare a couple of names
if p1 > p2
puts "#{p1.name}'s name > #{p2.name}'s name"
# => Matz's name > Guido's name
end
Thanks to Comparable
21. Comparable (cont’d)
# Sort an array of Person objects
puts "Sorted list:"
puts [p1, p2, p3].sort
# Guido
# Larry
# Matz
24. Crazy Syntax?
@observer_list ||= []
is equal to
@observer_list = @observer_list || []
If @observer_lists exist?,
assign it to @observer_list
else
assign [] to @observer_list
You may also consider this as either of them exist, assign it to
the instance variable