Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default value of a Struct attribute?

Tags:

ruby

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 
like image 809
N.N. Avatar asked Feb 24 '13 19:02

N.N.


People also ask

Can you set default values in a struct?

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.

Can structs have default values C++?

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.

What is the default value of the attribute?

The Default Value for an Attribute is the value that the Attribute has when the Entity Record or Structure is first intialized.

Does struct have default constructor?

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.


1 Answers

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

like image 80
rintaun Avatar answered Sep 28 '22 03:09

rintaun