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)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.