Skip to Main Content
Professional Ruby on Rails™
book

Professional Ruby on Rails™

by Noel Rappin
February 2008
Intermediate to advanced content levelIntermediate to advanced
479 pages
14h
English
Wrox
Content preview from Professional Ruby on Rails™

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher
Rails 4 in Action

Rails 4 in Action

Yehuda Katz, Rebecca Skinner, Stephen Klabnik, Ryan Bigg

Publisher Resources

ISBN: 9780470223888Purchase book