1. Classes are themselves represented as objects.
The first thing you’ll notice when you begin to learn ruby, is that all things are objects. Ruby is a dynamic 100% object oriented language (along with lots of others, as I seemed to have forgoten). This really opens the doors to a new type of programming, called meta-programming. Meta-programming allows you to open up classes and objects as the application is running and modify them in any way needed. Even classes are objects, and thus have their own set of methods available to them. Each time you create a class you’re actually creating an object of class Class. In the code below you’ll notice that Dog has lots of methods, but it doesn’t have a method named class. Dog can call the method “class” because it is an object of type class. This gives it access to all of ruby’s class object methods. A list of available methods for class Object can be found at Ruby Central. A more updated list can be found in the Programming Ruby 2nd Edition
class Dog
## lots of Dog methods that aren't def class
end
p Dog.class # => Class
2. Methods can be defined on a per-object basis
Methods can also be created for a specific instance of an object. These methods are only available to the the object named in the method call.
dog = Object.new
def dog.bark
puts "ruff ruff"
end
dog.bark # => ruff ruff
3. You can also define per-object methods using class << dog
You can also create objects by using the Object.new method. This now makes dog a certified object, and thus you are free to add methods to this object.
dog = Object.new
class << dog
def bark
puts "ruff ruff"
end
end
dog.bark # => ruff ruff
4. outside of methods, within a class … end block, self refers to the class
Self always references the current object. Inside of any class, self will be treated just the same as Dog (if you’re in class Dog).
class Dog
p self # => Dog
end
5. “class methods” are simply per-object methods defined on classes
In ruby, you are able to tie a class to a particular object. Remember from tip 4 that you can replace self with Dog, and nothing about the code would change. This use of self defines a class that is based around the object self. Here, self is the class object Dog. This now allows you to add methods to class Dog. These new methods are class methods, and will be available to Dog. This means that you don’t have to create an instance of this object to call this method.
class Dog
class << self
def bark
puts "ruff ruff"
end
end
end
Dog.bark # => ruff ruff
As you can see, ruby leaves the door wide open for you to modify all classes while your app is running.
(see more here: http://www.recentrambles.com)