January 2024
Intermediate to advanced
718 pages
20h 15m
English
If Data is the most immutable way to get a small object, OpenStruct is the most flexible. An OpenStruct isn’t a class generator, rather, it’s more a way to allow you to have hash-like data with attribute-like syntax.
You create an OpenStruct with new method, taking either a hash argument or an arbitrary set of keyword arguments. After that, you can read, write, and create attributes just by using them, and you can also use hash syntax:
| | require "ostruct" |
| | |
| | bulb = OpenStruct.new(brightness: 1600, watts: 15, color: 2500) |
| | bulb.color # => 2500 |
| | bulb[:watts] # => 15 |
| | bulb.shape = "A19" |
| | bulb.to_h # => {:brightness=>1600, :watts=>15, :color=>2500, :shape=>"A19"} |
Internally OpenStruct uses method_missing, which ...
Read now
Unlock full access