Reputation: 49
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
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:
The hash form has benefits:
class
as keysWhen writing new code, pick whichever form appeals the most.
Upvotes: 6