Ruby Struct at Depth
Struct.new builds a small class from a list of field names. This lesson uses keyword_init so every object is built with named fields.
Building a point with named fields
The Point class is built from the symbols x and y. keyword_init: true makes the new call name each field.
Point = Struct.new(:x, :y, keyword_init: true)
point = Point.new(x: 3, y: 4)
puts point.x
puts point.yListing the fields with members
members answers the field names as symbols. The order matches the order given to Struct.new.
Point = Struct.new(:x, :y, keyword_init: true)
p Point.membersComparing structs by value
Two points with the same field values compare as equal. A point with a different x value does not.
Point = Struct.new(:x, :y, keyword_init: true)
first = Point.new(x: 3, y: 4)
second = Point.new(x: 3, y: 4)
third = Point.new(x: 5, y: 4)
puts first == second
puts first == thirdReading the values as a hash
to_h pairs each field name with its current value. The keys are the same symbols passed to Struct.new.
Point = Struct.new(:x, :y, keyword_init: true)
point = Point.new(x: 3, y: 4)
p point.to_hExample
City = Struct.new(:name, :population, keyword_init: true)
city = City.new(name: "Oslo", population: 700)
city.population = 710
puts city.name
puts city.population
p city.to_hKey points
- Struct.new takes field names and returns a new class.
- keyword_init: true makes construction use named fields.
- members lists the field names in order.
- Each field gets a reader with the same name.
- Two structs are == when their fields hold equal values.
- to_h builds a hash from the field names and values.
- A struct is mutable, so a field can be set after construction.
In this example, City is a struct with name and population fields built with keyword_init. The population field is set to a new value after construction, which shows that a struct stays mutable. The final line reads the updated values back as a hash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Two structs from the same class hold the same field values. What does == between them give?