ruby

Ruby Class vs Struct


I have seen codebases using Structs to wrap around attributes and behavior inside a class. What is the difference between a Ruby Class and a Struct? And when should one be used over the other.?


Solution

  • From the Struct docs:

    A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

    The Struct class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor.

    So, if I want a Person class that I can access a name attribute (read and write), I either do it by declaring a class:

    class Person
      attr_accessor :name
    
      def initalize(name)
        @name = name
      end
    end
    

    or using Struct:

    Person = Struct.new(:name)
    

    In both cases I can run the following code:

     person = Person.new
     person.name = "Name"
     #or Person.new("Name")
     puts person.name
    

    When use it?

    As the description states we use Structs when we need a group of accessible attributes without having to write an explicit class.

    For example I want a point variable to hold X and Y values:

    point = Struct.new(:x, :y).new(20,30)
    point.x #=> 20
    

    Some more examples: