8

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 ?

5
  • 1
    What's your use case? Struct is great for things that don't have a lot of additional logic. Commented Jul 5, 2013 at 15:40
  • I just want your thoughts on this when you need to define classes with initializers. Since using Struct seems to be "sexier", I would like to know the drop-downs, if any. Commented Jul 5, 2013 at 15:46
  • If you have a specific use case, that's an on-topic question. If you just want to generate a discussion about the pros and cons of various implementations, that's not a good fit for the Q&A format. Commented Jul 5, 2013 at 15:54
  • 2
    Struct is not that useful for general case classes, any more than Hash is. 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. Commented Jul 5, 2013 at 15:56
  • @NeilSlater good point thx. @CodeGnome actually I use initializers a lot in my project right now and didn't know Struct before today. Commented Jul 5, 2013 at 15:58

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting! You definitely don't want to use them as Class if they don't behave like it then. Thx. I'll see what other people have to say about it and accept the answer accordingly :)
I think the right idea here is you use Struct for simple data containers, as an alternative to passing Hashes around, and use a proper Object when you're actually adding any sort of logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.