简体   繁体   English

Use keyword arguments vs hash arguments in Ruby class constructor?

[英]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.我是 Ruby 的新手,正在学习如何使用 Ruby 做正确的 OOP,我有一个问题,关于哪个是最惯用的方式来执行 ZABB1DZ2 构造函数。

I've seen a lot of examples using hash parameters to construct an object:我见过很多使用 hash 参数构造 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? Ruby 更推荐哪种方式,为什么? Many thanks in advance!提前谢谢了!

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.关键字 arguments 出现在 Ruby 2.0 中,因此一些较旧的代码库使用第一种方法( (params) ),特别是在保持与 Ruby 1.8 和 1 的兼容性时。

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: hash 表格具有以下优点:

  • 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可以使用class等保留关键字作为键

When writing new code, pick whichever form appeals the most.编写新代码时,选择最吸引人的形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM