Class
With classes in Ruby, we construct complex models. Classes have constructors: this is the initialize method. We invoke "initialize" with new()
calls.
By hiding information, classes help with complexity. Understanding objects is important in program design. It helps to know when classes are not needed.
Here we use a custom class
called Box. We add a constructor to this class
—in Ruby, the constructor is called initialize()
. The one here receives two arguments.
initialize()
, we assign 2 fields (width and height) to the arguments. Fields use a leading "at" character.class
fields.class
name (Box) and the new method. Box.new
returns a new instance of the Box class
.class Box # The constructor. def initialize(width, height) # Assign fields from arguments. @width = width @height = height end # A custom method. def display() puts @width puts @height end end # Create a new Box. x = Box.new(10, 5) # Call the display method. puts x.display()10 5
Classes use getters and setters to control access to their fields. This improves program design. It makes classes more separated from external code that uses them.
break
.class Box # Getter. def size @size end # Setter. def size=(number) @size = number end end # Create a new Box. x = Box.new() # Use setter. x.size = 10 # Use getter and display. puts x.size10
Each class
can have a to_s method defined. This method should return a string
that contains the class
data. We can specify a string
, and this is automatically returned as the result.
class
. The width and height fields are inserted into the string
.class
is passed to a method like puts, the to_s method is automatically invoked. This all happens implicitly.class Box def initialize(width, height) # Initialize the class. @width = width @height = height end def to_s # Return this string. "Box, width: #@width, height: #@height" end end # Create new Box. b = Box.new(10, 20) # Display it (calls to_s). puts bBox, width: 10, height: 20
One class
can inherit from another. The derived class
, a subclass, gains the abilities (like methods) from the parent class
. The "less than" operator indicates a subclass.
super()
we invoke a same-named method from the class
parent. So from Square's super()
we invoke Shape display()
.class Shape def display() puts("Shape display") end end # This class inherits from Shape. class Square < Shape def display() puts("Square display") # Call superclass method of the same name. super() end end # Create the class. item = Square.new() item.display()Square display Shape display
The self object is available in all classes. It refers to the immediate class
instance. We can access methods with self, or pass self to an external method.
test()
and pass it the self instance. The self variable evaluates to an object.def test(s) # See if the Shape's color is red. puts(s.color == "red") end class Shape def initialize(color) @color = color end def color @color end def analyze() # Pass this object to another method. test(self) end end # Create Shape and call the analyze method. s = Shape.new("red") s.analyze()true
Methods can be modified with visibilities. Public things can be called from external locations, outside of the class
. Something private is only used inside the class
.
class Navigator def initialize(location) @location = location end def location() update() @location puts @location end def update() @location = @location.upcase() end public :location private :update end # Create new class instance and call location public method. n = Navigator.new("japan") n.location()JAPAN
Let us get into some mischief. Here we try to call a private method, update()
from the same class
as above. We get a NoMethodError
. And the program terminates.
n = Navigator.new("japan") n.update()/Users/sam/Documents/test.rb:24:in '<main>': private method 'update' called for #<Navigator:0x007fa3cb082200 @location="japan"> (NoMethodError)
Module
This is an organization unit, much like a namespace in other languages. We use modules to organize classes and methods. To use a module in our file, we use the "include" keyword.
class
) within a module with two ":" characters. We access "Cat::meow
" as an example.module Cat def pet() puts "Cat petted" end end # Reopen and change the module (use mix-in). module Cat def meow() puts "Cat meows" end end # Include the module and call its methods. include Cat Cat::pet() Cat::meow()Cat petted Cat meows
Built around classes, Ruby has robust support for object-oriented programming. Classes encapsulate functionality and data, and they reside in memory.