Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...