0
0
RubyHow-ToBeginner · 3 min read

How to Create Object in Ruby: Simple Guide with Examples

In Ruby, you create an object by defining a class and then making an instance of it using ClassName.new. This creates a new object with its own data and behavior based on the class.
📐

Syntax

To create an object in Ruby, first define a class. Then use ClassName.new to make a new object (instance) of that class.

class defines a blueprint for objects.
new creates a fresh object from that blueprint.

ruby
class MyObject
  def initialize(name)
    @name = name
  end
end

obj = MyObject.new("Ruby")
💻

Example

This example shows how to create a class Car and then make an object from it. The object stores a name and can show it.

ruby
class Car
  def initialize(make)
    @make = make
  end

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

my_car = Car.new("Toyota")
puts my_car.show_make
Output
This car is a Toyota.
⚠️

Common Pitfalls

One common mistake is forgetting to use new to create an object, which causes errors because you are calling methods on the class itself, not an instance.

Another is not defining an initialize method properly, so the object does not get the data it needs.

ruby
class Person
  def initialize(name)
    @name = name
  end
end

# Wrong: missing .new
# person = Person("Alice")  # This will cause an error

# Right:
person = Person.new("Alice")
📊

Quick Reference

  • class ClassName: Defines a new class.
  • def initialize(params): Sets up new objects with data.
  • ClassName.new(args): Creates a new object.
  • @variable: Instance variable to hold object data.

Key Takeaways

Define a class to create a blueprint for objects in Ruby.
Use ClassName.new to create a new object (instance) of that class.
The initialize method sets up object data when creating it.
Always use .new to avoid errors when making objects.
Instance variables (starting with @) store data inside objects.