shou2017.com
JP

What is ruby's initialize method?

Tue Aug 1, 2017
Sat Aug 10, 2024

I couldn’t understand it in one look at the initialize method explanation in the reference, so I’ll summarize it here.

Object initialization method of a user-defined class.

This method is called to initialize a newly created object from Class#new. It is equivalent to the constructor in other languages. The default behavior is to do nothing.

initialize is passed the same arguments given to Class#new.

It is expected that subclasses will redefine this method as needed.

The method named >initialize is automatically set to private.

ruby2.4.0リファレンス

It’s easier to understand if you think in terms of concrete examples.

For example, consider a case where a character in a game has to have 100 HP when it is created. If the HP is 0 when creating a new character, the game is over immediately and there is no way to talk about it. To avoid such a situation, the HP is determined in advance.

This is expressed using initialize.

class Monster
  # HP-100
  def initialize(hp=100)
    @hp = hp
  end
  def hp
    puts(@hp)
  end
end
pikachu = Monster.new
pikachu.hp   #=> 100

Expressions without initialize

Of course, it can be done without initialize.

class Monster
  def hp=(hp)
    @hp = hp
  end
  def hp
    puts(@hp)
  end
end

pikachu = Monster.new
pikachu.hp = 100
pikachu.hp   #=> 100

There is no problem in this form, but if a team is making this game, mistakes may occur between the person who is making the big book Monster and the person who is making the individual monster pikachu or Zenigame.

Like, I thought the HP of Zenigame was 200. And if the value of HP is fixed from the beginning than anything else, it is better to use initialize.

If you put the initialize method in the class, it is convenient because it works automatically when the new method is executed.