Classes and the Class Class

I’ll warn you right now: this section is a bit of a brain bender, so if you’re not feeling particularly strong of stomach, you can skip to the next chapter. At least for now, it’s mainly of academic interest. But just in case you were wondering…

As you may have noticed, we can call methods on strings (things such as length and chomp), but we can also call methods on the actual String class, methods such as new. This is because, in Ruby, classes are real objects. (This isn’t the case in most languages.) And since every object is in some class, classes must be, too. We can find the class of an object using the class method:

puts(42.class)
puts(​"I'll have mayonnaise on mine!"​.class)
puts(Time.new.class) ​# No shocker ...

Get Learn to Program, 2nd Edition 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.