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
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.
When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.
The Default Value for an Attribute is the value that the Attribute has when the Entity Record or Structure is first intialized.
C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With