Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

ruby - How to change the default value of a Struct attribute?

According to the documentation unset attributes of Struct are set to nil:

unset parameters default to nil.

Is it possible to specify the default value for particular attributes?

For example, for the following Struct

Struct.new("Person", :name, :happy)

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)

I get

-:1: syntax error, unexpected '=', expecting ')'
Struct.new("Person", :name, :happy = true)
                                    ^
-:1: warning: possibly useless use of true in void context
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...