Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
 
Basic class definition and use in Ruby

WHY USE OBJECTS IN RUBY ANYWAY?

Single block code is great for short utility scripts, but as coding requirements grow you'll do better to move to a more structured approach, with named blocks of code ('methods' in Ruby) which will perhaps be spread around a number of files.

With further growth, an Object Oriented approach becomes much more logical; with OO, you can bind a method to an object or type of object, and then call up the method as appropriate. In other words, you can have several methods called 'length' - one of which returns the length of a cricket pitch, and another the length of a TV program. They'll work differently inside, but you ruby program will know which one to run when - the length of "The Oval" is clearly the length of a cricket pitch, and the length of "Emmerdale" is almost certainly half an hour!

Ruby's OO model is superb. It's pure, robust, trusting and not overcomplex as you'll learn in this module and beyond

DEFINING A CLASS

You define a class with a class statement, through to a nested end statement. Your class definition will contain methods to work on objects (class members) which are defined with defs, each also ending with an end.

A method called initialize is your constructor - in other words, you write a method called initialize which defines how you create an object in the first place.

Variables with names starting with an @ within your method definitions are instance variables. In other words, if you start a variable name with an @ you're saying that you're sharing that variable with all the other methods that you've def'd in the class, BUT that there's a different variable (of the same name) for each case (instance) of the class.

The variable "name" and "@name" are different - "name" is local to the current closure (you'll hear that word come up many times more), but "@name" applies to the current object; you may have used the word "this" or "self" to indicate the same thing in other programming languages. And, yes, you CAN have a variable called name and a variable called @name at the same time, pointing to different locations in memory and containing different information - and even different types of object.

By defining a class, you are NOT using it! You are simple saying what it would do IF you chose to use it ... which you'll probably do later in your code. After all, there would be no point in defining something just to have the definition go away when your program terminated.

Example: Defining a type of object called "person":

class Person

# Constructor - called 'initialize'.
# Variables with leading @ are instance (object) variables

   def initialize(name = "Mate")
      @name = name
   end

# methods to run on Person object

   def aussie
      print "Wotcha, #{@name}\n"
   end

   def usa
      print "Hi, #{@name}\n"
   end

end

MAKING USE OF A CLASS

Having defined a class, we need to make use of it. Use the new keyword/method to create object(s) (instances) of the class. This keyword causes the initialize method to be run. A reference to the newly created object is returned, which you can store in a variable (you can also do other things with it!).

Once you have created an object, you can run other methods that are available to members of that class on it.

Let's take our Person class, and create two people and greet them in Australia and in the USA:

starter = Person.new
starter.aussie

nextperson = Person.new("Betty")
nextperson.usa
nextperson.aussie

When we run that, we get:

earth-wind-and-fire:~/ruby/r105 grahamellis$ ruby myo.rb
Wotcha, Mate
Hi, Betty
Wotcha, Betty
earth-wind-and-fire:~/ruby/r105 grahamellis$

LOADING A CLASS FROM ELSEWHERE

You'll want to share your classes (and other code too) from other files, which you can do with a require.

Your main code looks like:

require "dp"

starter = Person.new
starter.aussie
starter.britain

nextperson = Person.new("Percy")
nextperson.usa
nextperson.aussie

and that will load (and evaluate - i.e. run) the file dp.rb when it executes the require statement.

We have the following in the dp.rb file:

class Person

   def initialize(name = "friend")
      @name = name
   end

   def aussie
      print "Wotcha, #{@name}\n"
   end

   def usa
      print "Hi, #{@name}\n"
   end

   def britain
      print "Hello, #{@name}\n"
   end

end

Other subjects that we'll look at later are: include, load, and specifying which directory the extensions are brought in from


See also Learning Ruby - training classes

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Ruby - Classes and Objects
  [4502] Reading and parsing a JSON object in Ruby - (2015-06-01)
  [4009] Clear, concise examples - Ruby classes and objects. - (2013-02-17)
  [3421] Ruby off the Rails? - (2011-09-06)
  [2651] Calculation within objects - early, last minute, or cached? - (2010-02-26)
  [2616] Defining a static method - Java, Python and Ruby - (2010-02-01)
  [2609] Scope of variables - important to Ruby on Rails - (2010-01-31)
  [2603] Ruby objects - a primer - (2010-01-29)
  [2292] Object Orientation in Ruby - intermediate examples - (2009-07-16)
  [1925] Introduction to Object Oriented Programming - (2008-12-06)
  [983] Blessing in Perl / Member variable in Ruby - (2006-12-14)

Ruby - More Classes and Objects
  [4551] Testing your new class - first steps with cucumber - (2015-10-23)
  [4550] Build up classes into applications sharing data types in Ruby - (2015-10-23)
  [4504] Where does Ruby load modules from, and how to load from current directory - (2015-06-03)
  [4366] Changing what operators do on objects - a comparison across different programming languages - (2014-12-26)
  [3782] Standard methods available on all objects in Ruby - (2012-06-23)
  [3781] Private, Protected, Public in Ruby. What about interfaces and abstract classes in Ruby? - (2012-06-23)
  [3760] Why you should use objects even for short data manipulation programs in Ruby - (2012-06-10)
  [3260] Ruby - a training example that puts many language elements together to demonstrate the whole - (2011-04-23)
  [3158] Ruby training - some fresh examples for string handling applications - (2011-02-05)
  [3154] Changing a class later on - Ruby - (2011-02-02)
  [3142] Private and Public - and things between - (2011-01-22)
  [2980] Ruby - examples of regular expressions, inheritance and polymorphism - (2010-10-02)
  [2977] What is a factory method and why use one? - Example in Ruby - (2010-09-30)
  [2717] The Multiple Inheritance Conundrum, interfaces and mixins - (2010-04-11)
  [2623] Object Oriented Ruby - new examples - (2010-02-03)
  [2620] Direct access to object variable (attributes) in Ruby - (2010-02-02)
  [2616] Defining a static method - Java, Python and Ruby - (2010-02-01)
  [2604] Tips for writing a test program (Ruby / Python / Java) - (2010-01-29)
  [2603] Ruby objects - a primer - (2010-01-29)
  [2601] Ruby - is_a? v instance_of? - what is the difference? - (2010-01-27)
  [2292] Object Orientation in Ruby - intermediate examples - (2009-07-16)
  [1587] Some Ruby programming examples from our course - (2008-03-21)
  [1217] What are factory and singleton classes? - (2007-06-04)
  [656] Think about your design even if you don't use full UML - (2006-03-24)
  [184] MTBF of coffee machines - (2005-01-20)

resource index - Ruby
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

1 unpublished comment pending on this page

edit your own (not yet published) comments

© WELL HOUSE CONSULTANTS LTD., 2019: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/ruby-bas ... -ruby.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard