Ruby: Struct vs Initialize

What are the advantages and disadvantages of using Struct over the definition of the initialize method?

I can already see that in the absence of an argument it includes less code and does not raise :

Using struct:

 class Fruit < Struct.new(:name) end > Fruit.new.name => nil > Fruit.new('apple').name => "apple" 

Using initialization:

 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? Do you Struct often in your projects?

+8
ruby ruby-on-rails ruby-on-rails-3
source share
1 answer

The class (non-structural) has a simpler tree of ancestors:

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

Compared to the structure version:

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

Thus, the Struct class could be mistaken for an array (rarely, but absolutely can happen)

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

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

+14
source share

All Articles