Session 8

Finish Tic Tac Toe (see Session-7)

Objects and Classes

Objects are data structures that have state and operations that change their state. Classes are definitions of objects. An object is an instance of a class. We've been working with objects and classes all along. Classes can have methods too. You create a new instance of a class by calling it's new method.

my_string = String.new # String is a class
my_string = '' # this is the same thing as String.new
puts my_string # my_string is an object
 
my_array = Array.new # Array is a class
my_array = [] # this is the same thing as Array.new
puts my_array.size # my_array is an object

Class names are always capitalized. You can find out what class an object is by calling it's class method

puts my_string.class
puts my_array.class

There are tons of objects built into ruby. Many more are available by importing libraries that you can download from the web. You can even write your own. In fact, all the programs we have written are actually changes made to an instance of Object running in ruby.

Yeah, you can make changes to an object while it's running.

Modules

I might as well talk about Modules here too. Modules are like classes, but they don't usually have any data. They are usually just a list of methods all packaged up together. You can "mix-in" a module into an object. When you do, that object gains all of the module's methods.

Some Classes

Here are some useful classes. They are all built-in to ruby. You can also find a list here.

Dir
Allows you to read the contents of a directory
File
Allows you to read the contents of a file, move it, rename it, see how big it is, etc.
Hash
Like an array, but you index it not with numbers, but objects
Math
A module containing useful math operations and constants
Object
The parent of all classes
Range
an interval of numbers or strings or other objects
Time
holds dates and times, allows you to get the time

We'll talk about reading and writing files at a later date. We'll also talk about how to make your own classes later.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License