Writing our own Class
A class is a combination of state (for example, the quantity and the product id) and methods that use the state.
The Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.
Let's write our own class - MotorCycle.rb.
Read this very carefully, it's a brain bender! Classes in Ruby are first-class objects - each is an instance of class Class. When a new class is defined (typically using class Name ... end), an object of type Class is created and assigned to a constant (Name. in this case). When Name.new is called to create a new object, the new instance method in Class is run by default, which in turn invokes allocate to allocate memory for the object, before finally calling the new object's initialize method.
A class's instance methods are public by default; anyone can call them. Let's refer to the program ClassAccess.rb below. The private directive is the strictest; private methods can only be called from within the same instance. Protected methods can be called in the same instance and by other instances of the same class and its subclasses.
Inheritance allows you to create a class that is a refinement or specialization of another class. Refer program Inherit.rb.
Technorati Tags: Writing our own Class
Blogs linking to this article
The Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.
Let's write our own class - MotorCycle.rb.
class MotorCycle
def initialize(make, color)
# Instance variables
@make = make
@color = color
end
def startEngine
if (@engineState)
puts 'Engine Running'
else
@engineState = true
puts 'Engine Idle'
end
end
def dispAttr
puts 'Color of MotorCycle is ' + @color
puts 'Make of MotorCycle is ' + @make
end
m = MotorCycle.new('Yamaha', 'red')
m.startEngine
m.dispAttr
m.startEngine
end
Read this very carefully, it's a brain bender! Classes in Ruby are first-class objects - each is an instance of class Class. When a new class is defined (typically using class Name ... end), an object of type Class is created and assigned to a constant (Name. in this case). When Name.new is called to create a new object, the new instance method in Class is run by default, which in turn invokes allocate to allocate memory for the object, before finally calling the new object's initialize method.
A class's instance methods are public by default; anyone can call them. Let's refer to the program ClassAccess.rb below. The private directive is the strictest; private methods can only be called from within the same instance. Protected methods can be called in the same instance and by other instances of the same class and its subclasses.
class ClassAccessInstance variables are not directly accessible outside the class. To make them available, Ruby provides accessor methods that return their values. The program Accessor.rb illustrates the same.
def m1 # this method is public
end
protected
def m2 # this method is protected
end
private
def m3 # this method is private
end
end
# Accessor.rbThere are many classes and modules (more on this later) built into the standard Ruby language. They are available to every Ruby program automatically; no require is required. Some built-in classes are Array, Bignum, Class, Dir, Exception, File, Fixnum, Float, Integer, IO, Module, Numeric, Object, Range, String, Thread, Time. Some built-in Modules are Comparable, Enumerable, GC, Kernel, Math. The following Class Hierarchy is informative.
# First without accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
def name
@name
end
def artist
@artist
end
end
song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist
# Now, with accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
# the instance variable @name and @artist will
# be automatically created below
attr_reader :name, :artist # create reader only
# For creating reader and writer methods
# attr_accessor :name
# For creating writer methods
# attr_writer :name
end
song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist
Inheritance allows you to create a class that is a refinement or specialization of another class. Refer program Inherit.rb.
class GF
def initialize
puts 'In GF class'
end
def gfmethod
puts 'GF method call'
end
end
# class F sub-class of GF
class F < GF
def initialize
puts 'In F class'
end
end
# class S sub-class of F
class S < F
def initialize
puts 'In S class'
end
son = S.new
son.gfmethod
end
First Post | Previous | Next
Technorati Tags: Writing our own Class
Blogs linking to this article





11 Comments:
Next week, I shall start with Rails. In case, there are some Ruby features that we require in Rails; I shall discuss the same at that point in time.
This comment has been removed by a blog administrator.
My Doubts:
1. def initialize(....) --> is this same as a constructor similar to in C++/Java.
2. Do I nedd to include [ def initialize (....) method ; if I am not passing any agrugments from object.
m = MotorCycle.new() # no argument
3. Do I need to create object always within the [ Class XYZ---- end ]block. Can't I create object outside the class?
Hi Satish,
A few questions around classes and inheritence.
1. Ruby, just like Java, only supports single inheritence and not multiple inheritence like C++. So does it allow interfaces?
2. Does Ruby allow abstract classes? And abstract methods?
3. Does Ruby allow polymorphism? If so, could you give an example please?
4. Is Ruby code always interpreted? Is there a bytecode or machine code convertor for Ruby?
5. Do we need to import libraries explicitly?
6. Does the name of the file have to match the name of the Class?
7. Can you define anonymous classes? Or internal classes?
8. Does Ruby allow object serialisation?
Sorry, I am just listing all my interview questions here :-).
This comment has been removed by a blog administrator.
Can we write inner classes in Ruby??
Hello,
I just wanted to know that
Can there be more than one constructors?
Sir,
I observed that we have to define function before the line that make a call to it. Like in MotorCycle.rb, if I place the function dispAttr just before the last end statement of class, then I get error.
# Hi Jai..I think we CANNOT use more than one constructor.[Constructors cant be overloaded] I tried the below Pgm. If you uncomment, it doesnt work then.
class MotorCycle
#def initialize()
# puts 'no argument'
# end
def initialize(just_one)
puts 'one argument'
end
puts "Just one constructor"
#puts "With Two constructor"
#obj1=MotorCycle.new();
obj2=MotorCycle.new('one');
end
Hi Satish,
Great!!! I look forward to getting onto Rails.
Regards,
Ashish.
I tried an example. No method overloading too ???
Post a Comment
Links to this post:
Create a Link
<< Home