Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Class vs Struct

Tags:

ruby

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.?

like image 982
rshetty Avatar asked Sep 16 '14 16:09

rshetty


People also ask

Is it better to use struct or class?

use struct for plain-old-data structures without any class-like features; use class when you make use of features such as private or protected members, non-default constructors and operators, etc.

Does Ruby have struct?

What is a Struct in Ruby? A struct is a built-in Ruby class, it's used to create new classes which produce value objects. A value object is used to store related attributes together.

What is the only difference between a struct and a class?

Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit.

Is struct more efficient than class?

The only difference between these two methods is that the one allocates classes, and the other allocates structs. MeasureTestC allocates structs and runs in only 17 milliseconds which is 8.6 times faster than MeasureTestB which allocates classes! That's quite a difference!


1 Answers

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).
like image 179
lcguida Avatar answered Sep 22 '22 01:09

lcguida