如何更改 Struct 属性的默认值? [英] How to change the default value of a Struct attribute?
问题描述
根据文档Struct 的未设置属性设置为 nil
:
According to the documentation unset attributes of Struct are set to nil
:
未设置参数默认为零.
是否可以为特定属性指定默认值?
Is it possible to specify the default value for particular attributes?
例如对于下面的Struct
For example, for the following Struct
Struct.new("Person", :name, :happy)
我希望属性 happy
默认为 true
而不是 nil
.我怎样才能做到这一点?如果我做如下
I would like the attribute happy
to default to true
rather than nil
. How can I do this? If I do as follows
Struct.new("Person", :name, :happy = true)
我明白
-:1: syntax error, unexpected '=', expecting ')'
Struct.new("Person", :name, :happy = true)
^
-:1: warning: possibly useless use of true in void context
推荐答案
这也可以通过将 Struct 创建为子类并覆盖初始化
使用默认值,如下例所示:
This can also be accomplished by creating your Struct as a subclass, and overriding
initialize
with default values as in the following example:
class Person < Struct.new(:name, :happy)
def initialize(name, happy=true); super end
end
一方面,这种方法确实会导致一些样板;另一方面,它可以很好且简洁地完成您想要的操作.
On one hand, this method does lead to a little bit of boilerplate; on the other, it does what you're looking for nice and succinctly.
一个副作用(根据您的偏好/用例,可能是好处也可能是烦恼)是您失去了所有属性的默认 Struct
行为,默认为 nil
-- 除非您明确将它们设置为如此.实际上,上述示例将使 name
成为必需参数,除非您将其声明为 name=nil
One side-effect (which may be either a benefit or an annoyance depending on your preferences/use case) is that you lose the default Struct
behavior of all attributes defaulting to nil
-- unless you explicitly set them to be so. In effect, the above example would make name
a required parameter unless you declare it as name=nil
这篇关于如何更改 Struct 属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!