JustDave
JustDave

Reputation: 546

Ruby object initialization: params, hash, vanilla?

I ran into some confusion over when/why or if it is just a matter of preference when initializing a method with a hash type structure.

class Person1
    attr_reader :name, :age
    def initialize(params)
        @name = params[:name]
        @age  = params[:age]
    end
end
    me = Person1.new(name: 'John Doe', age: 27)
    puts me.name
    puts me.age
#----------------------------------------------
class Person2
   attr_reader :name, :age
   def initialize(name, age)
        @name = name
        @age = age
   end
end
    me = Person2.new('John Doe',  27)
    puts me.name
    puts me.age
#----------------------------------------------
class Person3
   attr_reader :person
   def initialize(name, age)
       @person = { name: name,
                    age: age }
   end
end
    me = Person3.new('John Doe',  27)
    puts me.person[:name]
    puts me.person[:age]

If it is a matter of preference I like just passing the hash but I could see this being an issue if you need different attr reader, writer within the hash itself. Is there a rule of thumb? I see a lot of rails articles using params.

Upvotes: 0

Views: 1246

Answers (1)

Femaref
Femaref

Reputation: 61497

Your third way will most likely never appear in the wild - you are already constructing a person object, why does it have an accessor for person? The attributes should be on the class itself. The difference between 1 and 2 is mostly preference, but the second one can be advantageous when you regulary want to set only specific attributes.

Concering rails' usage of params: params is the hash that contains the request parameters of the particular request you are handling. As you deal with requests a lot in rails, it will appear in every controller and can also appear in some views.

Upvotes: 1

Related Questions