Intro to Ruby - Classes

Ruby

Overview

So things are getting interesting now that we get to talk about the blueprint of objects which are classes. The code below is a simple example of a class which uses constant, local, instance, and class variables as talked about earlier. Demonstration of instance and class methods are also shown including the use of the initialize (constructor) method. Take some time to study and play with the code.

Code

# A simple class.
class Human
LABEL = "Human"

def initialize arms = 2, legs = 2
@arms = arms
@legs = legs
@@label = "This is the class label for a variable."
end

def describe
puts "I have #{@arms} arm(s)."
puts "I have #{@legs} leg(s)."
end

def self.label
@@label
end

def self.what_am_i
puts "I am a #{LABEL}."
end
end

# An instance of the Human class is created for the following examples.
human = Human.new 1, 2

# The following calls the "describe" instance method which, in turn, prints the values of the @arms and @legs instance variables.
puts "01 Instance Variables and Methods\n\n"
human.describe

# The following calls the "what_am_i" class method.
puts "\n02 Class Method\n\n"
Human.what_am_i

# The following prints the value of the LABEL contanst using accessed via the scope operator (::).
puts "\n03 Class Constant\n\n"
puts Human::LABEL

# The following is a convenience method to access the the class variable: @@label.
puts "\n04 Class Variable\n\n"
puts Human.label

Output

01 Instance Variables and Methods

I have 1 arm(s).
I have 2 leg(s).

02 Class Method

I am a Human.

03 Class Constant

Human

04 Class Variable

This is the class label for a variable.

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 09-classes.rb.

What’s Next

Modules

Tags:

Monday, March 2nd, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.