Ruby – Initialize Method

This post will focus on creating and setting the states of an instance of a Class. It will also highlight how to render the parameters of the object through the puts methods by overriding the to_s method.

How do we create a class?

class Book

end

Note: Class will start with an uppercase letter and method will start with a lowercase letter

To instantiate an object from a class (i.e. create new instance of a class), we use the new method.

#this will create 2 instances of the class "Book"

bookone = Book.new

booktwo = Book.new

The problem with the above code is that both instances are identical. There is nothing to distinguish them from one another. They do not hold any state.

To solve this, we use the initialize method on the objects.

class Book

#method takes in two parameters which will set the object's state

def initialize(isbn, price)

#use instance variables to store the states of each object as it is constructed

@isbn = isbn

#float method takes its argument and converts it to a floating-point number.
#If conversion fails, there will be an error.

@price = Float(price)

end

end

If you are curious, this is how the initialize method works

Step 1: Book.new will create a new object. Ruby allocates some memory to hold uninitialized object.

Step 2: Calls initialize method and pass the parameters to new object.These parameters acts as local variables within the method. Logically, it follows the naming conventions of a local variable in Ruby.

Step 3: Transfer these “local variables” to their respective instance variables.

So if we create another object, it will appear like this

class Book
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
end

bookthree = Book.new("isbn1", 3)

p bookthree

Result = #<Book:0x007fbd42863d58 @isbn="isbn1", @price=3.0>

puts bookthree

Result = #<Book:0x007fbd42863d58>

So the difference between print and puts is that puts simply writes string to the output. It wrote the name of the object’s class followed by a colon and the object’s unique identifier.

It’s ugly, so we need to override the to_s method to render a more human-readable output.

class Book
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end

def to_s
"ISBN: #{@isbn}, price: #{@price}"
end

end

bookone = Book.new("isbn1", 3)

puts bookone

Result = ISBN: isbn1, price: 3.0

Notice how the instance variables are stored with each object and available to all the instance methods of those objects.

Moral of the story: The initialize method automatically add states to an instance upon instantiation.