-
Book Overview & Buying
-
Table Of Contents
Polished Ruby Programming - Second Edition
By :
The Struct class is one of the underappreciated Ruby core classes. It allows you to create classes with one or more fields, with accessors automatically created for each field. Instead of the following code, which uses a standard Ruby class:
class Artist
attr_accessor :name, :albums
def initialize(name, albums)
@name = name
@albums = albums
end
end
You can use a Struct, and have the initializer and accessor methods automatically created:
Artist = Struct.new(:name, :albums)
One of the more interesting aspects of Struct is how it works internally. For example, unlike the new method for most other classes, Struct.new does not return a Struct instance; it returns a Struct subclass:
st = Struct.new(:a, :b)
st.class
# => Class
st.superclass
# => Struct
However, the new method on the subclass creates instances of the subclass; it doesn't create future subclasses. Additionally, if you provide a string and not a symbol as the first argument...
Change the font size
Change margin width
Change background colour