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 here.
puts(Time.class) ​# A little more interesting...
puts(String.class) ​# Yeah, OK...
# Hold your breath through the tunnel, boys and girls!
puts(Class.class)
# <gasp!>
Fixnum
String
Time
Class
Class
Class

If this makes sense to you right now, then stop thinking about it! You might screw it up! Otherwise…don’t sweat it too much. Move on; let your subconscious do the work later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.25.4