14.3. Classes, Metaclasses, and Singletons
Consider the following irb session.
irb(main):001:0> "abcd".class => String irb(main):002:0> "abcd".class.class => Class irb(main):003:0> "abcd".class.class.class => Class irb(main):004:0> "abcd".class.class.class.class => Class
In this code, the abcd string is, like everything in Ruby, an object. Every object in Ruby belongs to a class. The class for abcd is, naturally, String. The class for the class String is the class Class.
It's hard to proceed from this point without sounding a little bit like a deranged Philosophy professor: "What is the meaning of self", "What is the essence of object?" "What is the nature of being a class?" "What does it mean if a class is also an object?" "If a class is an object, where do classes come from?"
14.3.1. Classes and Objects
A Ruby object has two essential features. It has some set of attributes, which define its state, and it belongs to a class, which defines its behavior. For example, in Soups OnLine, a Recipe object contains several pieces of data representing its state, including a title, a list of ingredients, and a description.
It also belongs to the Recipe class, which defines a number of useful things that the object can do with its data, such as converting it to XML. And Recipe is a subclass of ActiveRecord::Base, which defines a whole boatload of useful things to do with data. Similarly, the characters abcd represent the state of a String, and all the methods of String define what you ...
Get Professional Ruby on Rails™ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.