ruby basic3
TRANSCRIPT
Ruby Basic(3)Author: Jason
Content
Class
Inheritance
Module
Mixin
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
Class is mutableChange the method length of String
class String
def length
0
end
end
a = "I am a very long string"
a.length # => 0
Method though message
1.next # => 2
1.send(:next) # => 2
Class Exampleclass Book
def initialize(isbn, price)
@isbn = isbn
@price = price
end
end
book = Book.new("a book",100)
parameter from new
@xx are instance variable
Getter
def isbn=(isbn)
@isbn = isbn
end
Setter
def isbn
isbn
end
Generate getter & setter
class Book
attr_reader :isbn # => getter
attr_writer :isbn # => setter
attr_accessor :isbn # => getter & setter
.....
end
Access Control protected
def xxx
end
private
def yyy
end
Inheritanceclass Parent
def say_hello
"Hello "
end
end
class Child < Parent
end
c = Child.new
c.say_hello # => "Hello "
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 ::
Module Examplemodule Trig
PI = 3.1415
def Trig.sin(x)
...
end
end
require 'trig'
y = Trig.sin(Trig::PI/4)
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
Mixin Example
module Debug
def who_am_i?
"debug: #{self.to_s}"
end
end
Mixin Example(cont’d)class Person
include Debug
def to_s
"I am Person"
end
end
p = Person.new
p.who_am_i? # => "debug: I am Person"
include from Debug
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
Comparable Exampleclass Person
include Comparable
attr_reader :name
def initialize(name)
@name = name
end
Comparable (cont’d)
def to_s
"#{@name}"
end
def <=>(other)
self.name <=> other.name
end
end
Only method to implement
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
Comparable (cont’d)
# Sort an array of Person objects
puts "Sorted list:"
puts [p1, p2, p3].sort
# Guido
# Larry
# Matz
Instance variable in Mixin
There can be instance variables in Mixin,
Though the getter and lazy instantiation.
Lazy Loading Example
module Observable
def observer
@observer_list ||= []
end
...
endCrazy short cut
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