Ruby Struct

Structs: Simple Objects

Objective: Fancy hashes that responds to attributes names as a function, like in JS Objects

Car =, :maker, :year, keyword_init: true)

vw_up = model: 'Up!', year: 2015, maker: 'VW'
polo ='Polo', 'VW', 2018)
golf = 'Golf', 'VW'

# "VW"
# nil

Equality: It uses their attributes instead object ids like default classes

# vw_up2 = model: 'Up!', maker: 'VW', year: 2015
vw_up == vw_up2
# True

OpenStruct: Simpler alternative

require 'ostruct'

cat = 'black')
puts cat.class
puts cat.color

Differences from Struct

  • Struct creates a new class with predefined attributes, equality method (==) & enumerable
  • OpenStruct creates a new object with the given attributes