RFS: Object Initialization Part 2 - 013

In this episode we'll show you how to clean up object intialization. We'll take a look at how we can pass in multiple arguments without following the correct order.

Passing in Multiple Arguments via Hash

In the previous episode we left off our initialize method like so

def initialize(name, price)  @name = name  @price = priceend

What happens if we want to pass in 5 or even 6 arguments and we don't want to remember which order they have to be passed in. We might want to have something like this.

Product.new(price: 50, name: "God of War")

Let's explore hash parameters

def initialize(params)  puts paramsend
Product.new(name: "God of War", price: 50)=> {name: "God of War", price: 50}

Great! now we understand that ruby basically outputs a hash when we type our arguments in like the example above.

Assigning Instance Variable Dynamically

In ruby we have a method called instance_variable_set which is a part of the Object class

We can use this method to assign values from the hash to our instance variables.
def initialize(params)  params.each do |k, v|    self.instance_variable_set "@#{k}", v  endend

That's pretty much it! now we can pass int as many arguments as we want as hashes and it will automatically assign then as attributes in the object.