How to change the default value of a Struct attribute?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)