Tutorial - Ruby - Class And Modules


Coding Friends Tutorial Index - > Ruby

Author Ian - Tutorial Posts = 62
A Ruby class is very similar to the other programming languages class
structures.  They allow for code to be created within a single object that
can be reused etc, the code can have its own separate block of
variables/methods for that instance of the required task. It is able to be
inherited and extended which is different to a module which only allows for
the created module to have methods and constant variables.


module SillyModule      # module is a single instance object, e.g. they can have
methods and constants
  def hello
    "Hello."
  end
end

class SillyClass        # a class can include a module and expand on it, an class
can generate many instances (objects) of itself.

  include SillyModule   # also use the sillymodule as well.
  def bob
          "timing is everything."
  end

end
s = SillyClass.new
puts s.hello    # Hello.
puts s.class    # SillyClass - displays the class name
puts s.bob      # timing is everything


Save this code as class_module.rb, it will create a module that is included
within the SillyClass.  To demonstrate that the module is a single instance
of a object, if you try to create a new object, e.g. mod = SillyModule.new,
the compile will
class.rb:20: undefined method `new' for SillyModule:Module (NoMethodError)
since the new method is not part of a module but only a class.
Creation of cool tutorials :)

There is forum thread about tutorial here

User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search