Struct
is a collection of attributes with accessor methods.
A Struct
class generates a new subclass that contains a set of members and their values without having to write the class explicitly.
For each member, a reader and writer method is created that is similar to #attr_accessor
.
Vehicle = Struct.new(:make, :model)puts Vehicle.superclassputs Vehicle.ancestors
Since Struct
is bundled with the Enumerable
module,
we can take advantage of methods like #filter
, #count
, #include?
, #uniq
, #tally
, etc.
Vehicle = Struct.new(:make, :model)puts Vehicle["Dodge", "Hellcat"]bike = Vehicle.new("Triumph", "Daytona")puts bikebike.make = "Yamaha"bike["model"] = "R1"puts bike
We can pass in a class_name
argument that will then be scoped under Struct
to define the class.
puts Struct.new("Vehicle", :make, :model)puts Struct::Vehicle.new("BMW", "S1000RR")
When the class_name
argument is not passed:
Vehicle = Struct.new(:make, :model)puts Vehicle.new("BMW", "S1000RR")puts Struct.new(:make, :model)
Vehicle = Struct.new(:make, :model, :number_of_wheels) dodef bike?number_of_wheels == 2endendhellcat = Vehicle.new("Dodge", "Hellcat", 4)puts hellcat.bike?
Returns true
if other
has the same class and values for its members.
Object#==
is used for comparison.
Customer = Struct.new(:name, :address, :zip)joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)smith = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)puts joe == smith
#values
methodReturns values of its members as an array.
Customer = Struct.new(:name, :address, :zip)joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)puts joe.values
#members
methodReturns its members as an array.
Customer = Struct.new(:name, :address, :zip)joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)puts joe.members
#dig
methodExtracts the nested value.
Address = Struct.new(:lane, :city, :location_data)Customer = Struct.new(:name, :address)address = Address.new("123 Maple", "Anytown NC", { lane: { street: "123 Watson Street" }, zip: 12345 })joe = Customer.new("Joe Smith", address)puts joe.dig(:address, :location_data, :lane, :street)
In this post we have checked all the details about ruby’s Struct
class and some of its useful methods.
Free Resources