In the previous articles, we got into some of the simpler aspects of Ruby. In this tutorial, we are going to cover the area of Classes and Objects. While still pretty basic in concept, Classes and Objects are powerful tools that will assist in your efforts to take over the world -- or at least to master all of the wonderful things that Ruby can do.
Ruby Classes and Objects - Constructors: More than Meets the Eye (Page 3 of 4 )
In the above sample of code, the brand of soda always stays the same. But what if we want it to change? Well, we can use the class's constructor (the initialize method) to change it.
(Note: the constructor creates new objects as well as manipulates the data within them).
class Soda
def initialize(brand)
@brand = brand
end
def retrieve_brand
return @brand
end
end
soda = Soda.new("Pepsi")
puts "The soda brand is now " + soda.retrieve_brand
This will print the text: The soda brand is now Pepsi.
Attributes
In Ruby data items available outside of objects are known as Attributes. There are three types: Readable, Writeable, and Readable/Writeable.
To create a Readable attribute do the following:
class Soda
attr_reader :brand
def initialize(brand)
@brand = brand
end
end
soda = Soda.new("Dr. Salt")
puts "You are now drinking " + soda.brand
The result would be: You are now drinking Dr. Salt
The statement attr_read :brand creates an accessor method by the name (brand) and creates an instance variable of the same name (@brand). And that is how you create a readable attribute.
(Note: an accessor method allows you to access data inside an object).
To create a Writeable attribute do the following:
class Soda
attr_reader :brand
attr_writer :brand
def initialize(brand)
@brand = brand
end
end
soda = Soda.new("Pepsi")
puts "You are drinking " + soda.brand
soda.brand = "Dr. Salt"
puts "Sike...you are really drinking " + soda.brand
This outputs:
You are drinking Pepsi
Sike...you are really drinking Dr. Salt
Basically what happens is that you assign brand a value ("Pepsi"), read that brand and display it to the screen, then change the value using the writeable attribute to "Dr. Salt" and print that to the screen.
As you can see, we not only made a writeable attribute, but a readable one as well. There is a simpler method for creating a readable/writeable attribute however: