Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Struct vs Initialize

What are the advantages and disadvantages of using Struct versus defining an initialize method ?

I can already see that it involves less code and not raising when missing an argument:

Using struct:

class Fruit < Struct.new(:name)
end

> Fruit.new.name
 => nil
> Fruit.new('apple').name
 => "apple"

Using initialize:

class Fruit
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

> Fruit.new.name
ArgumentError: wrong number of arguments (0 for 1)
> Fruit.new('apple').name
 => "apple"

What are your thoughts ? Are you using Struct frequently in your projects ?

like image 621
Pierre-Louis Gottfrois Avatar asked Jul 05 '13 15:07

Pierre-Louis Gottfrois


People also ask

What does struct do 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 initialize method in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.


1 Answers

The class (non-struct) has a simpler ancestry tree:

>> Fruit.ancestors
=> [Fruit, Object, Kernel, BasicObject]

As compared to the struct version:

>> Fruit.ancestors
=> [Fruit, #<Class:0x1101c9038>, Struct, Enumerable, Object, Kernel, BasicObject]

So, the Struct class could be mistaken for an array (rare, but absolutely could happen)

fruit = Fruit.new("yo")
# .. later
fruit.each do |k|
  puts k
end
# outputs: yo

So... I use Structs as throw-away data objects. I use "real" classes in my domain and application.

like image 63
Jesse Wolgamott Avatar answered Oct 26 '22 09:10

Jesse Wolgamott