1. Introduction
In object-oriented programming, a class is a blueprint for creating objects. In Ruby, classes play a fundamental role, encapsulating both data and the methods to operate on that data. This guide will demonstrate how to define a simple class and create an instance of that class in Ruby.
2. Program Steps
1. Begin by using the class keyword followed by the class name, starting with a capital letter.
2. Inside the class, define any initial attributes and methods.
3. End the class definition with the end keyword.
4. Instantiate an object of the class using the .new method.
3. Code Program
# Define the class
class Dog
# Method to set the dog's name
def name=(value)
@name = value
end
# Method to retrieve the dog's name
def name
@name
end
# Method to make the dog bark
def bark
puts "#{@name} says Woof!"
end
end
# Create an instance of the Dog class
fido = Dog.new
# Set the dog's name
fido.name = "Fido"
# Call the bark method on the dog object
fido.bark
Output:
Fido says Woof!
Explanation:
1. The class keyword initiates the definition of the Dog class.
2. Inside the class, two methods are defined: name= (a setter method) and name (a getter method). These methods allow us to set and get the dog's name, respectively. Another method, bark, is defined to print a message when called.
3. We end the class definition using the end keyword.
4. We then create an instance of the Dog class using Dog.new and assign it to the variable fido.
5. Using the setter method, fido.name=, we set the name of the dog object to "Fido".
6. Finally, the bark method is invoked on the fido object, displaying the output message.
Classes provide a structured way to represent and interact with objects in Ruby, allowing for encapsulation and object-oriented programming practices.