Creating your own Ruby new method

I’ve been studying more of Ruby from RubyTapas and I even got back to an old project of mine, the RubyFarm. I’m here today to show one really cool thing that I learned today: how to personalize the new method.

In order to do that, Ruby needs from us three things (from RubyTapas):

1 – Allocate a new, empty object of the given class.
2 – Run any specialized initialization code defined for the class
3 – Return the initialized instance

So if we would rewrite the RubyFarm Animal new instance method, for example, we could do something like:

class Animal
  def self.create_new(*args, &block)
    instance = allocate
    instance.my_initialize(*args, &block)

  def my_initialize(breed, age, weight, last_vaccine)
    @breed = breed
    @age = age
    @weight = weight
    @last_vaccine = last_vaccine

bob = Animal.create_new('domestic cat', 5, 8, 2017)
p bob # => <Animal:0x00005644aaa17800 @breed="domestic cat", @age=5, @weight=8, @last_vaccine=2017>

And voil√†! Ruby really makes it easier to creates your own methods. Thanks, Avdi for all of those lessons ūüôā

Hope you found that as awesome as I did when I learned this. See you next time!