Chapter 9: Classes: By: Kushal Jangid
Chapter 9: Classes: By: Kushal Jangid
Chapter 9: Classes: By: Kushal Jangid
By:
Kushal Jangid
Introduction
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]
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
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