Skip to content

Instantly share code, notes, and snippets.

@moxley
Last active August 29, 2015 13:59
Show Gist options
  • Save moxley/10689371 to your computer and use it in GitHub Desktop.
Save moxley/10689371 to your computer and use it in GitHub Desktop.
Struct-like objects in Ruby

Struct-Like Objects

  • 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment