If you want an object that can store some data the struct class is what you’re looking for.
In this post you’ll learn how to create structs, the difference between Struct & OpenStruct, and a few things you should watch out for.
A struct is a way to create a new class for the whole purpose of being a data container.
You can create an Struct by passing a list of symbols that’ll become the instance variables of this class.
They will have accessors defined by default, both for reading & writing:
person = Struct.new(:name, :age, :gender)
Now you can create new objects of this class with
john = person.new "john", 30, "M" puts john.age puts john.class
There are some differences with a “normal” class that you should be aware of.
For example, you may have noticed that the class of our
john object is just “Class”…
…to change this, you can do one of the following:
# Option 1 - Assign to a constant Person = Struct.new(:name, :age, :gender) # Option 2 - Subclass class Person < Struct.new(:name, :age, :gender) end
Both of these options will cause your new objects to have the class name you want.
Another caveat with Struct-generated classes is that they won't enforce the correct number of arguments for the constructor.
For example, with a proper class you would see this error:
ArgumentError: wrong number of arguments (0 for 3)
But if you are using Struct the missing arguments will be nil:
Person.new("peter") # struct Person name="peter", age=nil, gender=nil
Keep this in mind when working with Struct!
If you just need a one-off object, then you should consider using OpenStruct instead.
require 'ostruct' cat = OpenStruct.new(color: 'black') puts cat.class puts cat.color
The main difference with Struct is that it just produces objects, in other words, you can't call
cat.new in the example above to get more objects like it.
As long as you are aware of the special characteristics of each of these clases you will be fine.
Now go and start coding!