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 ?
Structis great for things that don't have a lot of additional logic.Structseems to be "sexier", I would like to know the drop-downs, if any.Structis not that useful for general case classes, any more thanHashis. It has some nice syntax for simple things, but the shortcuts this allows makes it difficult to do other important stuff such as data type validation.initializersa lot in my project right now and didn't knowStructbefore today.