Class & Module
Ruby is a perfect Object-Oriented Programming Language. An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.
Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
Table of contents
Class
Every object created by Class, Class is an important concept in Ruby. class and instance like Taiyaki fish mold and Taiyaki(Japanese fish-shaped cake). 
Ruby can use class method new to create an object from class. We can use instance method class to know the instance created by which class.
ary = Array.new
p ary #=> []
str = "Hello world."
p ary.class #=> Array
p str.class #=> String
use instance_of? to check this instance belongs to the class or not
ary = []
str = "Hello world."
p ary.instance_of?(Array) #=> true
p str.instance_of?(String) #=> true
p ary.instance_of?(String) #=> false
p str.instance_of?(Array) #=> false
Define a class
# hello_class.rb
class HelloWorld # class name
def initialize(myname = "Ruby") # initialize method
@name = myname # initialize myname, default value is Ruby
end
def hello # instance method
puts "Hello, world. I am #{@name}."
end
end
foo = HelloWorld.new("foo")
bar = HelloWorld.new("bar")
ruby = HelloWorld.new
foo.hello #=> Hello, world. I am foo.
bar.hello #=> Hello, world. I am bar.
ruby.hello #=> Hello, world. I am Ruby.
- class name first character should uppercase.
- in this case above,
foo,barandrubyare instance. - method
initializewill use in.new("foo"), and it will pass the parameter to parametermyname,and assign to instance variable@name - instance variable will start
@, and this kind of variable can read in instance.class HelloWorld ┊ def hello # hello is an instance method puts "Hello, world. I am #{@name}." end ┊ end foocreated by HelloWorld, whenfoocall instance method will returnHello, world. I am foo.
Attribute accessor
We need to define some method to read/write attributes(like @name)
# hello_class.rb
class HelloWorld
┊
def name # read @name
@name
end
def name=(value) # write @name
@name = value
end
┊
end
Then it can use two method name and name=
foo = HelloWorld.new("foo")
foo.name #=> "foo"
foo.hello #=> Hello, world. I am foo.
foo.name = 'foo_2'
foo.name #=> "foo_2"
foo.hello #=> Hello, world. I am foo_2.
Ruby has method for accessor with parameter by symbol(ex :name)
| attr_reader :name | only method for read |
| attr_write :name | only method for write |
| attr_accessor :name | both methods for read and write |
another word
class HelloWorld
┊
def name # read @name
@name
end
def name=(value) # write @name
@name = value
end
┊
end
same with
class HelloWorld
attr_accessor :name
┊
end
special variable self
self is a special variable that points to the object that “owns” the currently executing code.
# hello_class.rb
class HelloWorld
attr_accessor :name
def initialize(myname = "Ruby")
@name = myname
end
def reflect
self
end
end
foo = HelloWorld.new("foo")
foo == foo.reflect #=> true
that’s mean, self in instance methods is the object created by Class HelloWorld
In instance method hello, #{name} same with #{self.name}, self can be omitted.
# hello_class.rb
class HelloWorld
┊
attr_accessor :name
def hello # hello is an instance method
puts "Hello, world. I am #{self.name}."
end
┊
end
Assign value to variable in instance method
self CAN’T be omitted
def test_name
name = "Ruby" # assign "Ruby" to local variable name
self.name = "Ruby" # self is the object and call method name=
end
Class method
use self in method, it’s class method.
another word, self in class method is the class itself
# hello_class.rb
class HelloWorld
┊
def self.reflect
self
end
┊
end
HelloWorld.reflect == HelloWorld
Constant
it can define constant in class, The first character should uppercase.
# hello_class.rb
class HelloWorld
Version = "1.0"
┊
end
p HelloWorld::Version #=> "1.0"
private method
We don’t want to let all instance call in public, it can use private some problem.
# acc_test.rb
class AccTest
def pub
puts "pub is a public method."
end
public :pub # public is default, this line can be omitted
def priv
puts "priv is a private method."
end
private :priv # set priv is private method
end
acc = AccTest.new
acc.pub #=> pub is a public method.
acc.priv #=> in `<main>': private method `priv' called for
#<AccTest:0x007fb4089293e8> (NoMethodError)
Module
namespace
Ruby developer will use same naming style, like size or start
It will duplicate, but we can use namespace to solve this problem
# check file exist?
p FileTest.exist?("/usr/bin/ruby") #=> true
# check file size
p FileTest.size("/usr/bin/ruby") #=> 1374684
Mix-in
We can use model mix-in to refactor some method used in many class
# part of mix-in.rb
module MyModule
def hello
puts "Hello, world. I am #{@name}."
end
end
class HelloWorld
attr_accessor :name
include MyModule
def initialize(myname = "Hello")
@name = myname
end
end
class HelloRuby
attr_accessor :name
include MyModule
def initialize(myname = "Ruby")
@name = myname
end
end
HelloWorld.new('foo').hello #=> Hello, world. I am foo.
HelloRuby.new('bar').hello #=> Hello, world. I am bar.