Opus_A
Opus_A

Reputation: 49

Use keyword arguments vs hash arguments in Ruby class constructor?

I'm new to Ruby and learning how to do proper OOP with Ruby, and I have a question regarding which is the most idiomatic way for doing class constructors.

I've seen a lot of examples using hash parameters to construct an object:

class Person
    def initialize(params)
        @name = params[:name]
        @age = params[:age]
    end
end

person = Person.new(name:"Pepsi", age:42)

However, I've seen another way that I found clean and effective as well:

class Person
    def initialize(age:, name:)
        @name = name
        @age = age
    end
end

person = Person.new(name:"Pepsi", age:42)

Which way is more recommended in Ruby and why? Many thanks in advance!

Upvotes: 2

Views: 1128

Answers (1)

tadman
tadman

Reputation: 211740

They're both valid. Keyword arguments came about in Ruby 2.0 so some older code-bases used the first approach ((params)), especially when maintaining compatibility with Ruby 1.8 and 1.9.

The keyword form has benefits:

  • You'll be notified of typos
  • You can easily specify defaults
  • Method signature communicates which options exist

The hash form has benefits:

  • Won't complain about extra values
  • Can be adapted to be indifferent to string vs. symbol keys
  • Can use reserved keywords like class as keys

When writing new code, pick whichever form appeals the most.

Upvotes: 6

Related Questions