Initialize V .New — Ruby

Christopher Breen
2 min readDec 18, 2020

No this is not the next great running title of a Batman V Superman movie. This is a brief overview of the .new and initialize method in ruby. What are .new and initialize, well the initialize method is and instance method and a part of the object-creation in ruby it allows you to set the initial values for an object. Where as the .new is a class method that creates an instance of the class.

Let’s say we have a Human Class, this human needs a name and and age how can we pass these values into the object ?

The .new method is how we create the new object in Ruby from our Human class. The two arguments we passed in ‘Chris” & 27 will result in an error if we don’t define our initialize method because our Human class does not call for any arguments to be defined.

With the initialize method defined we can pass those two arguments into our new Human and because we’re using instance variables ‘@name = name’ . Lastly defining initialize is not needed if your class doesn’t require arguments.

--

--

Christopher Breen
Christopher Breen

Written by Christopher Breen

Leader in Hospitality turned hopeful coder learning to become a software engineer.

No responses yet