How to change the default value of a Struct attribute?

ruby

Solution

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`

Problem

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 ```

Original source