Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Binary Soul4,592 Points
Struct != Class
can someone explain me, in easy words, what is the benefit of using a struct instead of a class? I cant see why i should use this complicated construct if i can build up a class like always.
Jason SeiferTreehouse Guest Teacher
Hey Binary Soul! Structs are typically used when you just need a couple of getter/setter variables and methods without the need for a whole class. Or just as a shortcut. They're interchangeable for simple things:
Treehouse = Struct.new(:name, :website)
In practice, this is mostly the same as writing the following:
class Treehouse attr_accessor :name, :website end
Conventionally, if you're adding a bunch of methods to a Struct, it may be time to create a class.
The struct documentation even says it:
A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.