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
Following @rintaun's example you can also do this with keyword arguments in Ruby 2+
UPDATE
The code now needs to be written as follows to work.