I’ve been doing a lot of Ruby lately. Ruby was created in 1995 by Matz. The language itself is a mixture of Smalltalk, Perl, and Lisp. It uses infix message passing and everything is an object, including “primitives”. The language is designed for programmer joy. From Matz:

“Often people, especially computer engineers, focus on the machines. They think, “By doing this, the machine will run fast. By doing this, the machine will run more effectively. By doing this, the machine will something something something.” They are focusing on machines. But in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves.” – Yukihiro Matz

Methods in ruby are defined by the def keyword. Parenthesis can be omitted. Methods can be suffixed with characters like ?, !, =, etc, and each conventionally carries some meaning. In the case above the name= method will allow us to use assignment. The initialize method is the constructor and is called when you call Person.new. The @ prefix on a variable indicates it’s an instance variable (these are always private). When calling methods the parenthesis are again optional, which is why our usage of the assignment method above doesn’t need parenthesis. We could have written it like this and it would be functionally identical:

someperson.name=('Joe')

One of the key things you’ll discover about Ruby is that it aims to increase developer happiness by removing unnecessary cruft. As it turns out, the above example can be simplified like so:

classPersonattr_accessor:namedefinitialize(name)@name=nameendend

attraccessor generates code using the :name symbol. The code it generates is essentially what we saw in the first example, with getters/setters. Also available is attr_reader which generates just the getter, and attr_writer that generate just the setter.

So what’s that weird :name thing? It’s a symbol, which can be thought of as a global constant identifier. Symbol use in Ruby is extensive and you see them everywhere.

Traditional inheritance in Ruby is accomplished like this:

classStudent<Personend

If you’re familiar with inheritance in other languages you won’t be surprised about Ruby (except a few corner cases). But there is another inheritance possible in Ruby and its called a ‘mixin’: