RFS: Object Initialization Part 1 - 012

When we call the .new method on our class we are initializing the object. Ruby calls the initialize method. By default ruby handles this for us when we define a class however we can define the behavior of the initialize method ourselves.

Defining Initialize

class Product  TYPES = ['game', 'food']    attr_accessor :name, :price    def initialize(name, price)    @name = name    @price = price  endend

In this example we have an intialize method that will automatically set the name and the price attribute of our object. We can now pass arguments into the .new method.

game = Product.new("God of War", 50)

We now initialize the product with a name and a price all in 1 line.

Setting the instance variable in this manner can be very efficient however if we have 5-10 attributes in our class it might get repetitive to have to define 10 arguments and set 10 instance variables. In the next part we will explore how we can further clean up this code.