DEV Community

Sandip Mane
Sandip Mane

Posted on

Struct class in Ruby

Struct is a collection of attributes with accessor methods,
without having to write the class explicitly.

A Struct class generates a new subclass that contains a set of members and their values.
For each member, a reader and writer method is created similar to #attr_accessor.

> Vehicle = Struct.new(:make, :model)
> Vehicle.superclass
=> Struct

> Vehicle.ancestors
=> [Vehicle, Struct, Enumerable, Object, Kernel, BasicObject]
Enter fullscreen mode Exit fullscreen mode

Since Struct is bundled with Enumerable module,
we can take advantage of methods like #filter, #count, #include?, #uniq, #tally etc.

Example

> Vehicle = Struct.new(:make, :model)

> Vehicle["Dodge", "Hellcat"]
=> #<struct Vehicle make="Dodge", model="Hellcat">

> bike = Vehicle.new("Triumph", "Daytona")
> bike
=> #<struct Vehicle make="Triumph", model="Daytona">

> bike.make = "Yamaha"
> bike["model"] = "R1"
> bike
=> #<struct Vehicle make="Yamaha", model="R1">
Enter fullscreen mode Exit fullscreen mode

Follow the link for complete article https://www.sandipmane.dev/struct-class-in-ruby

Top comments (0)