Chapter 12
New Classes of Objects

So far we’ve seen several kinds, or classes, of objects: strings, integers, floats, arrays, a few special objects (true, false, and nil), and so on. In Ruby, these class names are always capitalized: String, Integer, Float, Array, File, and Dir. (You remember back here when we asked the File class to open a file for us, and it handed us back an actual file, which we called, in a fit of rabid creativity, f? Those were the days…. Anyway, we never ended up needing an actual directory object from Dir, but we could have gotten one if we had asked nicely.)

File.open was a mildly unusual way to get an object from a class. In general, you’ll use the new method:

alpha = Array.new + [12345] ​# Array addition.
beta = String.new + ​'hello'​ ​# String addition.
karma = Time.new ​# Current date and time.
puts ​"alpha = ​#{alpha}​"
puts ​"beta = ​#{beta}​"
puts ​"karma = ​#{karma}​"
alpha = [12345]
beta = hello
karma = 2013-06-15 22:59:02 -0700

Because we can create array and string literals using […] and ’…’, we rarely create them using new. (Though it might not be clear from the example there, String.new creates an empty string, and Array.new creates an empty array.) Also, numbers are special exceptions: you can’t create an integer with Integer.new. (Which number would it create, you know?) You can make one only using an integer literal (just writing it out as you’ve been doing).

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

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