Intro to Ruby - Classes

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
Article Series - Intro to Ruby
- Intro to Ruby - Getting Started
- Intro to Ruby - Strings
- Intro to Ruby - Numbers
- Intro to Ruby - Ranges
- Intro to Ruby - Arrays
- Intro to Ruby - Hashes
- Intro to Ruby - Variables and Scopes
- Intro to Ruby - Methods
- Intro to Ruby - Blocks
- Intro to Ruby - Classes
- Intro to Ruby - Modules
- Intro to Ruby - Conditionals
- Intro to Ruby - Loops
- Intro to Ruby - Exceptions
- Intro to Ruby - Testing
- Intro to Ruby - Next Steps
No comments yet.
Leave a comment
You must be logged in to post a comment.
Search
Categories
- Adventures
(145)
- Announcements
(39)
- Business
(20)
- Electronics
(22)
- Employment
(1)
- Epicurean
(10)
- Games
(2)
- Literature
(1)
- Mechanical
(4)
- Meetups
(15)
- Movies
(2)
- Music
(26)
- Photography
(1)
- Services
(27)
- Software
(134)