- Inspired by C's struct
- Situations where Hashes are used
- Why do we use hashes?
- Group key-value data together under one value
- Why don't we choose normal objects instead?
- Needs explicit class definition (false)
- Need place for class to live (false)
- When to use hashes over struct-like objects
- Infinite/unknown possible keys
- Ex: HTTP request params
- Advantages of stuct-style objects over hashes
- The option to dynamically-generate values (via explicit methods) without affecting dependents
- Implementation can change without affecting dependents
- It's an object, with object notation
- Can be converted to full-blown class-based object without affecting dependents
- Drawbacks of
Struct
- Positional initialization arguments
- No implicit definition possible
- Mutable
- Drawbacks of
OpenStruct
- No explicit definition possible
- Mutable
- No protection against unknown messages
Comparative Features:
API | Object Syntax | Schema | Implied Schema | Initializer Style | Immutable |
---|---|---|---|---|---|
Hash | No | No | No | Key-Value | No |
Struct | Yes | Yes | No | Positional | No |
OpenStruct | Yes | No | No | Key-Value | No |
ImmutableStruct | Yes | Yes | Optional | Key-Value | Yes |
MutableStruct | Yes | Yes | Optional | Key-Value | No |