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 ?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With