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
You can do this with a singleton:
This can also be accomplished by creating your Struct as a subclass, and overriding
initialize
with default values as in the following example: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 tonil
-- unless you explicitly set them to be so. In effect, the above example would makename
a required parameter unless you declare it asname=nil
@Linuxios gave an answer that overrides member lookup. This has a couple problems: you can't explicitly set a member to nil and there's extra overhead on every member reference. It seems to me you really just want to supply the defaults when initializing a new struct object with partial member values supplied to
::new
or::[]
.Here's a module to extend Struct with an additional factory method that lets you describe your desired structure with a hash, where the keys are the member names and the values the defaults to fill in when not supplied at initialization:
I think that the override of the
#initialize
method is the best way, with call to#super(*required_args)
.This has an additional advantage of being able to use hash-style arguments. Please see the following complete and compiling example:
Hash-Style Arguments, Default Values, and Ruby Struct
I also found this:
Just add another variation: