Ruby Classes and Objects - Create a Class
(Page 2 of 4 )
Creating a class is simple; all you need to do is use the class statement, like so:
class Soda
end
Classes follow a naming convention that insists the first letter must be capitalized. To add a method to a class, try the following:
class Soda
def initialize # initialize method is used to create objects
@brand = "Mountain Dew" # store value in @brand
end
def get_brand # method to return the value of @brand
return @brand
end
end
What we did above is create a class named Soda. We then added a method to the class, initializing an instance variable (stores the data in an object and exists as long as the object does). You'll notice that our friend the instance variable starts with an @ symbol; all instance variables must start this way to tell the program that it is indeed an instance variable.
You also stored data in the @brand variable and created a method to return the value of it (in this instance, "Mountain Dew").
Create an Object
To create an object in Ruby you use the new method.
class Soda
def initialize
@brand = "Mountain Dew"
end
def retrieve_brand
return @brand
end
end
soda = Soda.new # creates the Soda object
puts "The brand of the soda is " + soda.retrieve_brand
You'll note that our soda object uses the naming convention of starting with a lowercase letter. Since the soda object has the retrieve_brand method built into it, you can call it like we did in the last line of code. Do you want to see what the program will print on your screen? Then run the program you lazy bum. Sheesh.
The brand of the soda is Mountain Dew
Ta da! You've created a class and an object.
Next: Constructors: More than Meets the Eye >>
More Ruby-on-Rails Articles
More By James Payne