Ruby Class vs Struct

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:

  • http://blog.steveklabnik.com/posts/2012-09-01-random-ruby-tricks–struct-new
  • “When to use Struct instead of Hash in Ruby?” also has some very good points (comparing to the use of hash).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)