0
0
Rubyprogramming~5 mins

Instance methods in Ruby

Choose your learning style9 modes available
Introduction

Instance methods let objects do things or show information about themselves. They help organize code by grouping actions with the data they belong to.

When you want each object to have its own behavior, like a dog barking or a car driving.
When you need to get or change information stored inside an object.
When you want to keep related code together inside a class for easy understanding.
When you want to reuse code by calling methods on different objects of the same type.
Syntax
Ruby
class ClassName
  def method_name
    # code here
  end
end

Instance methods are defined inside a class using def.

You call instance methods on an object created from the class.

Examples
This defines a bark method for Dog objects.
Ruby
class Dog
  def bark
    puts "Woof!"
  end
end
This creates a Dog object and calls its bark method, printing "Woof!".
Ruby
dog = Dog.new
dog.bark
This method takes a name and says hello to that person.
Ruby
class Person
  def greet(name)
    puts "Hello, #{name}!"
  end
end
Calls the greet method with "Alice", printing a greeting.
Ruby
person = Person.new
person.greet("Alice")
Sample Program

This program creates a Car object with make and model. The description method returns a string describing the car. We print that description.

Ruby
class Car
  def initialize(make, model)
    @make = make
    @model = model
  end

  def description
    "This car is a #{@make} #{@model}."
  end
end

my_car = Car.new("Toyota", "Corolla")
puts my_car.description
OutputSuccess
Important Notes

Instance methods can access instance variables like @make inside the object.

You must create an object (instance) of the class to use instance methods.

Use initialize method to set up initial values when creating an object.

Summary

Instance methods belong to objects and define what they can do.

Define instance methods inside a class using def.

Call instance methods on objects created from the class.