Nothing Special   »   [go: up one dir, main page]

Chapter 9: Classes: By: Kushal Jangid

Download as odp, pdf, or txt
Download as odp, pdf, or txt
You are on page 1of 28

Chapter 9: Classes

By:
Kushal Jangid

Introduction

Ruby is an object-oriented programming (OOP) language, and that the


centerpiece of OOP is the class. A class is a container of sorts that
holds methods and properties such as variables and constants
(collectively known as class members). One of the most important
things about classes is that they can be reused by means of
inheritance.

Defining the Class


A class is defined with the class keyword, followed by an end . The
class identifier is a constant, so it must be capitalized (the norm).
class Hello
def initialize( name )
@name = name
end
def hello_matz
puts "Hello, " + @name + "!"
end
end
hi = Hello.new( "Matz" )
hi.hello_matz # => Hello, Matz!

Array Class
class Array
def array_of_ten
(1..10).to_a
end
end
arr = Array.new
ten = arr.array_of_ten
p ten # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Instance Variables
An instance variable is a variable that is available from within an
instance of a class, and is limited in scope because it belongs to a
given object.
class Horse
@name = "Easy Jet"
end
You have no way to retrieve the value of @name directly from the
outside.
h = Horse.new
h.name

Error

Instance Variable
You must define a method to retrieve the value.
class Horse
def name
@name = "Easy Jet"
end
End
h = Horse.new
h.name # => "Easy Jet"

Setter Method
class Horse
def name
@name
end
def name=( value )
@name = value
end
End
h = Horse.new
h.name= "Poco Bueno"
h.name # => "Poco Bueno"

Intialization Method
Class Horse that initializes the instance variable @name with the standard
initialize method. Later the program creates an instance of the class by calling
new , and then accesses the instance variable through the accessor method
horse_name , via the instance horse .
class Horse
def initialize( name )
@name = name
end
def horse_name
@name
end
End
horse = Horse.new( "Doc Bar" )
puts horse.horse_name # => Doc Bar

Accessors

[attr]

Ruby simplifies the creation of getters and setters with a little


metaprogramming and the methods attr , attr_reader , attr_writer , and
attr_accessor , all from the Module class.
The method attr creates a single getter method, named by a symbol, with
an optional setter method (if the second argument is true ),
class Dog
attr :bark, true
End
Dog.instance_methods - Object.instance_methods # => ["bark", "bark="]
dog = Dog.new
dog.bark="Woof!"
puts dog.bark # => Woof!

attr_reader
The method attr_reader automatically creates one or more
instance variables, with corresponding methods that return (get)
the values of each method. The attr_writer method automatically
creates one or more instance variables, with corresponding methods
that set the values of each method.

Simple Program
class Dog
attr_reader :bark
attr_writer :bark
End
dog = Dog.new
dog.bark="Woof!"
puts dog.bark # => Woof!
dog.instance_variables.sort # => ["@bark"]
Dog.instance_methods.sortObject.instance_methods # => [ "bark", "bark=" ]

attr_accessor
Calling the attr_accessor method does the same job as calling both
attr_reader and attr_writer together, for one or more instance
methods
class Gaits
attr_accessor :walk, :trot, :canter
end
Gaits.instance_methods.sort-Object.instance_methods
# => ["canter", "canter=", "trot", "trot=", "walk", "walk="]

Repeat Program
class Repeat
@@total = 0
def initialize( string, times )
@string = string
@times = times
end
def repeat
@@total += @times
return @string * @times
end
def total
"Total times, so far: " + @@total.to_s
end
end

Repeat Program
data = Repeat.new( "ack ", 8 )
ditto = Repeat.new( "Again! ", 5 )
ditty = Repeat.new( "Rinse. Lather. Repeat. ", 2 )
puts data.repeat # => ack ack ack ack ack ack ack ack
puts data.total # => Total times, so far: 8
puts ditto.repeat # => Again! Again! Again! Again! Again!
puts ditto.total # => Total times, so far: 13
puts ditty.repeat # => Rinse. Lather. Repeat. Rinse.
Lather. Repeat.
puts ditty.total # => Total times, so far: 15

Class Methods
A class method is a method that is associated with a class (and with
a module in Ruby), not an instance of a class. You can invoke class
methods by prefixing the name of the method with the name of the
class to which it belongs. Class methods are also known as static
methods.

Class Methods
class Area
def Area.rect( length, width, units="inches" )
area = length*width
printf( "The area of this rectangle is %.2f
%s.", area, units )
sprintf( "%.2f", area )
end
End
Area.rect(12.5, 16)
# => The area of this rectangle is 200.00 inches.

Singletons
Another way you can define class methods is by using a class within a
classa singleton class.
class Area
class << self
def rect( length, width, units="inches" )
area = length*width
printf( "The area of this rectangle is %.2f
%s.", area, units )
sprintf( "%.2f", area )
end
end
end
Area.rect(10, 10)
# The area of this rectangle is 100.00 inches.=> "100.00"

Inheritance
Ruby supports single inheritance, which means that a class can inherit only
one other classthe parent or superclass. When a child class inherits or
derives from a parent, it has access to the methods and properties of the
parent class. Inheritance is accomplished with the < operator.

Inheritance Program
class Name
attr_accessor :given_name, :family_name
end
class Address < Name
attr_accessor :street, :city, :state, :country
End
a = Address.new
puts a.respond_to?(:given_name) # => true
The method respond_to? tests to see whether an instance of Address
hasaccess to :given_name , inherited from the Name class. The answer is
yes ( true ).

Inheritance Program
name.rb

class Name
attr_accessor :given_name, :family_name
end
address.rb
require 'name'
class Address < Name
attr_accessor :street, :city, :state, :country
End
a = Address.new
puts a.respond_to?(:given_name)

Modules
In addition to classes, Ruby also has modules. A module is like a
class, but it cannot be instantiated like a class.

Case Conversion

"Ruby finally has a killer app. It's Ruby on Rails.".capitalize


# => "Ruby finally has a killer app. it's ruby on rails."

Public, Private, or Protected


A class member marked public is accessible by anyone from anywhere; it
is the default.
private means that the receiver for the method is always the current
object or self , so its scope is always the current object.
A method marked protected means that it can be used only by instances
of the class where it was defined, or by derived classes.

Example time
class Names
def initialize( given, family, nick, pet )
@given = given
@family = family
@nick = nick
@pet = pet
end

Example time
# these methods are public by default
def given
@given
end
def family
@family
end

Example time
# all following methods private, until changed
private
def nick
@nick
End
# all following methods protected, until changed
protected
def pet
@pet
end
end

Example time
name = Names.new( "Klyde", "Kimball", "Abner", "Teddy Bear" )
name.given # => "Klyde"
name.family # => "Kimball"
# see what happens when you call nick or pet
name.nick
This will show Error
name.pet

Thank You

You might also like