I don't have much programming experience. But, to me, Struct seems somewhat similar to Hash.
- What can Struct do well?
- Is there anything Struct can do, that Hash cannot do?
After googling, the concept of Struct is important in C, but I don't know much about C.
From the Struct documentation:
On the other hand, a Hash:
The main difference is how you access your data.
In short, you would make a new Struct when you want a class that's a "plain old data" structure (optionally with the intent of extending it with more methods), and you would use a Hash when you don't need a formal type at all.
If you're just going to encapsulate the data, then a Hash (or an Array of Hashes) are fine. If you're planning to have the data manipulate or interact with other data, then a Struct can open some interesting possibilities:
I know this question was almost well-answered, but surprisingly nobody has talked about one of the biggest differences and the real benefits of
Struct
. And I guess that's why somebody is still asking.Struct
is faster.Structs differ from using hashmaps in the following ways (in addition to how the code looks):
Struct.new(:x).new(42) == Struct.new(:x).new(42)
is false, whereasFoo = Struct.new(:x); Foo.new(42)==Foo.new(42)
is true).to_a
method for structs returns an array of values, whileto_a
on a hash gets you an array of key-value-pairs (where "pair" means "two-element array")Foo = Struct.new(:x, :y, :z)
you can doFoo.new(1,2,3)
to create an instance ofFoo
without having to spell out the attribute names.So to answer the question: When you want to model objects with a known set of attributes, use structs. When you want to model arbitrary use hashmaps (e.g. counting how often each word occurs in a string or mapping nicknames to full names etc. are definitely not jobs for a struct, while modeling a person with a name, an age and an address would be a perfect fit for
Person = Struct.new(name, age, address)
).As a sidenote: C structs have little to nothing to do with ruby structs, so don't let yourself get confused by that.
One more main difference is you can add behavior methods to a Struct.