Skip to content

Instantly share code, notes, and snippets.

@emptyflask
Last active September 7, 2021 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emptyflask/aa38009a4fafcff4e005e480fb4af147 to your computer and use it in GitHub Desktop.
Save emptyflask/aa38009a4fafcff4e005e480fb4af147 to your computer and use it in GitHub Desktop.
Struct/OpenStruct/Hash

Struct for throwaway objects, OpenStruct only when keys may change, or you have a hash and must have accessor methods.

# Fastest, needs to initialize a Struct first
T = Struct.new(:name)
t1 = T.new('test')
t1.name # => 'test'
t1.foo # => error!

# Fast, needs to use hash lookups
t3 = {name: 'test'}
t3[:name] # => 'test'
t3[:foo] # => nil

# Slow, convenient
t2 = OpenStruct.new(name: 'test')
t2.name # => 'test'
t2.foo # => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment