In the eyes of ruby, 0 is true

Unlike many other languages, 0 isn’t qualified as false in an expression. For example :

a=0
if(a)
  #0 is true, so the code gets here
end

To Ruby, only 2 things are false : false and nil. I should rather say : An instance of FalseClass and an instance of NilClass. Everything else is true. 0 is a Fixnum instance and therefore is considered to be true.
How ruby can return false when you write if(3>5) then? The answer is quite simple : It is false because 3>5 (or should I say 3.>(5)) returns an instance of FalseClass.
I thought it was something important to note as this unusual definition of truth can cause some headaches to the unwary…

3 steps to understand how classes and objects work in ruby

I made a simple list describing the 3 main things to consider when trying to understand how objects work in ruby. Feel free to add to this list as much as you want. Your comments are welcome and very appreciated.

1) The starting point is the object, not the class

To understand how objects and classes behave in ruby, we have to stop thinking in terms of classes and start thinking in terms of objects. Why? Because in ruby, a class is also an object. Every classes you are defining are instances of a class named Class. Each of these instances contains everything related to the structure of the object. Only one instance for each class definition is needed in a typical ruby / rails application. I mean, there would be no need to have both String.new() and String2.new(). Just one factory to create String instances is enough. However, if for some strange reason you would like to clone the definition of a class in another instance, you could still do it.

String2 = Class.new(String)
my_string = String2.new("How useful!")
my_string.reverse

2) An object structure is not frozen and can be altered at any time

When you’re done defining your class and you put the end keyword, don’t think that this object (remember, a class is an object) is “safe” from future modifications, it isn’t. Everyone can modify your class structure. I know that dynamic languages are not for everyone (I imagine Java and C++ programmers shaking their heads in desperation right now…), but I personally find the freedom that they offer to be truly amazing.

class NoOneIsSafe
  def my_method
    "I'm in my_method"
  end
end
#Now, let's create a mess
def im_hacking_this_object!
  "Muhahahahaha!"
end
#I just realized that the following code does not what
#I really thought it would. Read the update below
NoOneIsSafe.send(:public, :im_hacking_this_object!)
obj = NoOneIsSafe.new
obj.im_hacking_this_object! #output : Muhahahahaha!

#UPDATE 03/30/2007
Even if the above code really changed NoOneIsSafe structure, I realized that it also changed the structure of every single instances! Whatever you write some_obj.methods, String.methods, MyCustomClass.methods, you will see the im_hacking_this_object! method everytime. It’s definitely NOT something a sane person would want to do.
You could also add a method to a single instance of an object, like this :

class NoOneIsSafe
  def my_method
    "I'm in my_method"
  end
end
obj=NoOneIsSafe.new
obj2=NoOneIsSafe.new
def obj.my_other_method
  "I exist in this instance only"
end
obj.my_other_method #it works
obj2.my_other_method #won't work

3) Things that don’t look like objects often are

When trying to understand how objects work in ruby, you have to put the following sentence in the back of your head at all time : “Objects are everywhere… even if I can’t always see them“. A trivial statement like result = 5 + 3 must be understood the following way :

  • The “+” method of the Fixnum instance named “5” is called
  • The Fixnum instance named “3” is passed as a parameter to the “+” method.
  • The result of the call is a FixNum instance and is assigned to an object called “result”, which in turn becomes a FixNum instance

I talk about those hidden OO mechanisms in the following articles :
Oh Ruby, who are you trying to fool?
A trap to avoid with Ruby assignments
#UPDATE 03/31/2007
Gary Wright pointed out that you can only have one instance for a given Fixnum. For example, if you write :
a=1
b=1
c=1
1, a, b and c will all point to the same space in memory (Actually, these are not 4 different references to the same object. they are the same object). When you write 5 + 3, 5 already is a FixNum instance. The name of this instance is 5. Thanks to Gary for clearing this out.

An introduction to symbols

Symbols in Ruby are used everywhere and for good reasons. There are two main reasons of using them instead of strings (however they are absolutely not a replacement to strings, more on that later).
1. Semantics
When you write :dog, it is clear that you are refering to something. On the opposite, when you write “dog”, it only looks like the letters d, o and g. If you remove the double quotes, dog magically gets a meaning.
2. Efficiency
When ruby sees a symbol for the first time, it creates a space in memory for it. Every other use of the same symbol will refer to that space instead of being allocated a new one. Same thing, same place.
This is all fine and dandy, but what are symbols exactly?

A symbol is an instance of class Symbol

In this regard it isn’t different than any other ruby object. The way it differs is in how you use the object. A Symbol instance is used differently than an instance of an other class. First, you cannot create a Symbol instance that way :

my_symbol = Symbol.new() # <== won't work!

To create a new Symbol instance, you simply have to use it like if it already existed. When ruby parses your code and finds a symbol for the first time, it creates an instance for it. The next time it will find the same object name (the name of the symbol) in your code, it will use the same space in memory (like any other object!).
So, to summarize : A symbol is simply an object with a special naming convention. The convention is that you must precede your symbol name with a colon ":" so ruby can understand that you want an instance of the Symbol class. Since Symbol.new() doesn't work, there had to be some way to create an instance of this class... that's exactly the purpose of the ":" character.

We don't care about what's contained inside a Symbol instance, we just care about it's name

While there are several instance methods you can call in a Symbol object, most of the time you are only interested by it's name. The purpose of a symbol is to centralize a meaning. You want to create names that will have a meaning for you and other programmers who may have to deal with your code later. You can think of symbols as an application wide registry table with 2 columns. The first column being the symbol object id (ex : 243938) and the second column being an associated name (ex : dog). Since we are humans and words have more meaning than numbers, we use the 2nd column to refer to a symbol.

Assignments

If you access a symbol directly, that is with the :symbol_name notation,you can't assign to it. It wouldn't make a lot of sense anyway. It's like if you were saying that the left object was a symbol and, at the same time, that it was a String. However, if you assign a symbol to an object, future assignments to this object are allowed.

:my_symbol = "blabla" # <== won't work!
container = :my_symbol # <== that's ok
container = :my_other_symbol # <== that's ok
container = "not a symbol" # <== that's ok

Comparing symbols to strings

If you write :dog == "dog", ruby returns false. It is because you are comparing a string with a Symbol instance. It just cannot be the same. If for some reason you would like to check if some string is equal to the name of a symbol, you would have to write :dog.to_s == "dog". Most of the time however, you will compare a Symbol instance with another Symbol instance.

my_var = :my_new_symbol #symbol created and assigned to my_var
my_other_var = :my_new_symbol #SAME symbol assigned to my_other_var
puts my_var==my_other_var #it's true!
puts my_var==:my_new_symbol #it's true!

Symbols are not better strings

Strings are all about content, symbols are all about meaning. When you write "dog", the three letters are the only things that matter. If you decide to use the String form of a "dog", it should be because you want to display the 3 letters on the screen or manipulate them in some way (capitalize, chomp!, reverse etc). When you write :dog, it is what a dog represents to your application that matters, not the individual letters. We only use words to define a symbol because we cannot use mental images (ruby is great, but that would be asking a bit too much...).

Symbols in hashes

You are probably comfortable using symbols with hashes already. animals[:dog] = "charlie" is something you see really often in ruby programs. As you might know, what the statement animals[:dog] = "charlie" really means to ruby is animals.[]=(:dog,"charlie"). The first parameter is a Symbol instance and the second parameter is the new value you want to store in the hash at the position associated with :dog. Every items in a hash are represented by a key and a value. In this specific case, the key is a Symbol instance. The []= method checks if there exists an item in the collection with the key part equals to the Symbol instance :dog. If it is the case, the 2nd parameter "charlie" is assigned to the value part of that same item.

A trap to avoid with ruby assignments

Another thing that’s pretty confusing for ruby new comers is the assignment operator (the “=” sign).
When you write something like : my_obj = MyClass.new, the “=” sign does what you think it does. However, when you write : my_obj.yadayada = “123”, it doesn’t (Ruby has a tendency to fool people).

Why is this second form of assignment any different?

In the second example, it seems like we are trying to set the attribute yadayada of my_obj, but that is impossible because ruby doesn’t allow this. As soon as it sees the dot after an object name, it expects to see a method, nothing else. Ruby doesn’t want you to play with the attribute of an object directly, it wants you to call it’s accessor methods.
If that is so, why didn’t Ruby complained when we wrote my_obj.yadayada = “123” ? It is a clear attempt to set an object attribute directly! Hmm, maybe it isn’t. Look closely. As much as it looks like a standard assignment, it is indeed a method call. When you write my_obj.yadayada = “123”, Ruby understands : my_obj.yadayada=(“123”). The “=” sign being the last character of the method name, that is : yadayada=.
If you don’t define the yadayada= method in MyClass, Ruby will complain by raising the following exception :
NoMethodError: undefined method ‘yadayada=’ for #MyClass:0x2c9be70.
As you can see, it is expecting a method, nothing else. That’s why you have to name your attribute writers with a trailing “=” if you want to give the illusion that an assignment occured. As for attribute readers, you have to give them the same name as the real attributes.

class MyClass
  def initialize()
    @yadayada = "initial value" #The real attribute
  end
  #Attribute reader
  def yadayada()
    @yadayada
  end
  #Attribute writer
  def yadayada=(some_value)
    @yadayada=some_value #real assignment! no more fooling
  end
end
#using the class
my_obj=MyClass.new()
puts(my_obj.yadayada) #calls the instance method "yadayada"
my_obj.yadayada = "some value" #calls the instance method "yadayada="

Congrats, mister Copperfield, the illusion is perfect! I’d like to point out that if the only thing your accessors are doing is to respectively get and set the real attribute value, you could use one or more of the following helpers at the beginning of your class : attr_reader, attr_writer and attr_accessor. For example, if you write attr_accessor :yadayada, your two accessors for the yadayada attribute will be created automatically for you. If you only want an attribute reader, use attr_reader. If you only want an attribute writer, use attr_writer.

A last twisted case

What if we write : my_hash[:my_key] = “some value” ?
It looks like a “real” assignment don’t you think? How can a method be named “[:my_key]=” ? It doesn’t make any sense. Well, I know… but ruby did something funky once again.
Question : What is the method name in my_hash[:my_key] = “some value” ?
Answer : []=
No kidding, []= is an instance method in the Hash class.
If Ruby was evil, it would force us to write the last statement in the following way : my_hash.[]=(:my_key,”some value”). We would all become completely crazy and it would be dangerous to our health. Fortunately, Ruby isn’t evil, it is our friend. It let us refer to our hash in a comprehensive manner so we don’t lose our mind. Then, it does some tricks we don’t want to know in the background that will transform :

my_hash[:my_key] = "some value"

to

my_hash.[]=(:my_key,"some value")

Phew… you won’t have to use the 2nd form, ever. I wonder what would people say about ruby if it was the case. But just in case you’re curious or doubtful, run IRB and write the following :

apple = {:color => "green", :variety => "granny smith"}
apple.[]=(:color,"red")
apple.inspect

An introduction to hashes

If you’re somewhat familiar with ruby, there are good chances that you won’t learn anything new and exciting in this article. However, if you’re new to the language or just didn’t have time to take a look at ruby hashes yet, maybe you should continue reading.

What is a hash ?

A hash is a collection of objects, exactly like an array. The difference with arrays though, is that the indexes of a hash are not represented with integer values (FixNum instances). Instead, the key can be an object of any type! This means that instead of accessing your hash this way : result = my_hash[4], you can access it this way : result = my_hash[‘the_thing_im_looking_for’] or, to do things in a more rubyish manner : result = my_hash[:the_thing_im_looking_for]. To create a new hash from scratch, you just have to specify the various key/value pairs and separates them with the hash literal “=>” :

animals = { :dog => "charlie", :cat => "kwiki", :mouse => "squeaky" }

Why should I use hashes ?

One of the obvious advantages with hashes is their readability. When you write animals[4], it’s quite hard to see which animal you are trying to get. When you write animals[:dog], it becomes pretty obvious. A maybe less obvious but extremely useful thing about hashes is that you can improve the way you pass parameters to your methods by making them more flexible. When you use this technique, the order of the parameters becomes totally irrelevant! Ruby helps you along the way to achieve this. Let’s see how :
First : let’s take a look at the method call

dance_like_an_idiot(:frequency => "every minute",
			   :idiocy_level => "REALLY idiot",
			   :risk => "losing credibility forever")

Now, let’s take a look at that dance_like_an_idiot method

def dance_like_an_idiot(params)
  puts(params[:frequency]) # writes "every minute"
  puts(params[:idiocy_level]) # writes "REALLY idiot"
  puts(params[:risk]) # writes "losing credibility forever"
  #instructions to start the idiotic dance
end

The first thing you’ll notice is that even though you passed 3 parameters to the method, that method accepted just one. What is going on here? Well, you know ruby is your friend and that a friend is always there to help you, right? Well, in that case you won’t be surprised to learn that it did something really cool for you in the background. The other thing you will notice is that we passed our parameters in an unusual way to our method. For each parameter, we specified a key/value pair separated by the “=>” literal. If you remember, it looks really similar to the way we created our hash from scratch earlier in this article. In fact, that’s exactly what happened. The one difference is that we didn’t assign the key/value pairs to an object. The twist is exactly there : Ruby did it for you (I told you he was your friend). Ruby created an “anonymous” hash on the fly with the key/value pairs you specified when calling the dance_like_an_idiot method. The new created hash then has been passed to the params parameter at the receiving end. From there, the dance_like_an_idiot method was able to use the hash in any way it wanted to.
The great thing about this technique is that you don’t have to care about the order in which you pass your parameters to a method because those parameters will get merged into a single hash anyway. You can even omit to specify a key/value pair and the method will still be called (if the method tries to use an item in the hash that hasn’t been specified by the caller, it will in fact be dealing with a nil object (external link)).
You can also pass both standard parameters and a hash to a method. However, if you do so, the order in which you pass those parameters will become important.
For example :

#given the following method declaration :
def dance_like_an_idiot(normal_parameter1,normal_parameter2,params)
  puts(normal_parameter1)
  puts(normal_parameter2)
  puts(params[:frequency])
  puts(params[:idiocy_level])
  puts(params[:risk])
  #instructions to start the idiotic dance
end
#you could write :
dance_like_an_idiot("bleh","blah",:risk=>"be considered as a moron")
#but you couldn't write :
dance_like_an_idiot(:risk=>"getting beat down","bleh","blah")

Hashes do not replace arrays

Even though a hash is more flexible than an array, it must be noted that since the hash keys are not numerical values (FixNum instances), it cannot be ordered as easily. The other disadvantage is that it is less performant than arrays for the same reason. Still, ruby hashes are extremely useful. Most of the time you will prefer a hash to an array for the added flexibility.

Oh Ruby, who are you trying to fool?

In every single languages that I know the existence, every arithmetic, bitwise and conditional operators are built-in and global keywords. Well, once again, Ruby had to do things differently. You might be surprised to learn that most ruby operators are not built-in keywords. Fine you’ll tell me… but what are they then?

Instance methods

What? Yes. I’m afraid to tell you that Ruby is trying to fool you badly. The least we could say is that Ruby is a language who took the OO principles very seriously… in some kind of obsessive way (but we like it for this). Let’s look at it concretly :

def do_something_clever
  result = first_number + 18
end

Beware! Ruby is trying to make you believe that “+” is independent from “first_number” and “18”. Meeeeeeeep! (I just tried to reproduce the irratating sound that you hear on a quiz show when some guy gives a wrong answer. Although I admit it sounded more like the road runner on crack) The “+” sign is not a “sign” at all. It is an instance method of our object called “first_number”, which is a Fixnum. And what is 18? 18 is the parameter for the “+” method, of course!
We almost succeed to unmask ruby’s diabolical plans to fool our poor mind, so hold on. If “+” is an instance method of the Fixnum class, then where the hell is the dot between that so called method and our object? Well, that’s where the fooling occurs. For the sake of readability, Ruby lets you write an arithmetic expression the way you’re used to. Then, it does some magic behind the scene. It adds a dot, trims the spaces and somehow manage to transform the arithmetic expression in a standard object method call.
*** Update : Like JC pointed out, it also takes care of operator precedence. So when you write 5+8*5 in IRB (ruby interpreter accessible by command line), it correctly gets tranformed to 5.+((8).*(5)). Note that I don’t know exactly what kind of magic ruby does. I just know for sure that “magic happens somehow” ***
So :

result = first_number + 18

means the following to Ruby :

result = first_number.+(18)

If you really wanted to, you could very well write all your arithmetic expressions the way it is illustrated in the 2nd example, but then people would start hating you and soon you wouldn’t have any friend left. Is this what you want? I don’t think so. Still, I think it’s important to know what’s really happening behind the scene when you write an arithmetic expression.
The same holds true if you use numbers directly in your expression, that is, without storing them in some named objects. In fact, in these cases the name of the object is the number itself. This means that once again, you could have done : result = 5.+(3) and thus taking the unnecessary risk to lose all your friends while living a life of misfortune and pain. Again, that’s not what you want, so I suggest you stick with result = 5 + 3. This last paragraph has been edited on 03/31/2007, thanks to Gary Wright.
Finally, here is how the “+” method declaration looks like :

class Fixnum
  #some implementation
  def +(other)
    #some internal call I am unaware of that does the actual addition
  end
end

As simple as that. All of this gives some strength to the statement : “In ruby, everything is an object”, don’t you think?
#UPDATE 03/29/2007
Thanks to Joseph Wright who brought to my attention that the same thing was possible in smalltalk. I wasn’t aware.
[talking about smalltalk…]
When you define a method, it can either be infix (also called binary), which allows for e.g. ‘5 + 5′, where ‘+’ is the method; unary, which has just one argument, or keyword, which looks like ‘methodName Arg1: Arg2:’
[end quote]

Is Rails too big?

My 2 triabulle friends and me joined forces to work on a web project. Emile pushed hard and convinced both Dan and me to use cakePHP. My first choice was obviously Rails but still I was happy because it would give me the opportunity to try the PHP MVC framework for the first time. Well, I tried it and liked it. It doesn’t have all the features nor the “polished look” that rails may have, but it does the job very, very well.
One of the things that hit me was how light cakePHP could be (pssst! it’s a directory structure, nothing else). The framework’s core php files are located in a sub-folder called cake, that’s it. No installation, no generators, no command-line tools, niet. cakePHP really is a lightweight framework.
Still, Rails remains my environment of choice. First, ruby is a language i enjoy a billion times more than PHP and that in itself is a good reason to stick with the popular framework. Add to this a great variety of neat features that Rails offers like unit testing and database migrations and you have a winner. However, sometimes I find Rails a little too big for my taste. I’d love it if I just had to upload a rails application on a shared host without having to make sure that it is correctly “installed”. I’d like Rails to be like cakePHP on that front. I mean, if some host got Apache (with mod_rewrite), a mysql/postgresql server and the latest ruby interpreter installed, then I’d like to be able to run a rails app right from the get go.
Do you also have the feeling that Rails might be a little too big?

Bring your methods to life with punctuation

One of the little things that makes ruby so different is the fact that you can use punctuation in the name of your methods. I could really well be wrong on this, but I think ruby is the only language that allows a programmer to name his method logged? for example. Oh well, I should play it more safe. Let’s say that ruby is the only language I know that allow this.
It’s great because just by looking at the question mark, you know what the method is all about and that it will (should) return yes or no. The other punctuation character you can use is the exclamation (!). It is generally used to announce some kind of destructive action or something that is unusual. The “!” sign is used a lot in Rails ActiveRecord methods. For example, you can call both myObject.save and myObject.save!
What is the difference? myObject.save! will raise an exception if something went wrong in the process of saving the object back to the database while myObject.save will remain silent.
What’s your take on using punctuation in method names? Is it a useful feature or just flash in the pan?

The one thing with Ruby that won you

Think of all the things in ruby that impressed you when you first start using it and try to remember the one that won your heart. It doesn’t has to be a key concept or a complex principle. A simple twist in the syntax that had you say “Wow… I love this!” could do.
To me, the Integer times method is that thing.
Loops like 3.times{puts “dum “} simply blow my mind by their readability. At that time I was wondering how this thing could work since I didn’t know about code blocks, but it still was a real pleasure to my eyes nonetheless. The times method might not be the end of the world, but it’s simple things like that that help me remember why I’m a proud rubyist.
What is the one thing with Ruby that won you ?

6 reasons why you should try Ruby

I love Ruby. I first learned about it on the Internet several months ago and decided I wanted to give it a try. I was intrigued by the kind of buzz around it. I felt that the Ruby crowd was smaller than the PHP, C# or even python crowd, but those who liked Ruby seemed to like it A LOT. I went to the ruby website and decided to try the online tutorial. At this moment, I just knew this thing was for me. I didn’t know exactly why at the time, but I knew that this language would become my language, my little favorite. Ruby would become the language I would defend proudly in a geek crowd wearing my transformers pajama.
So here we go with another “top ten” kind of post that is so popular on the blogosphere these days : 6 reasons why you should try ruby

1) Enjoy the power of code blocks!

Code blocks are chunks of code that can be passed to any ruby function. They take the form of anonymous functions and can be used to achieve a lot of useful things. One of the main use of ruby code blocks is to achieve what we could call “intelligent loops”. Instead of managing the internals of the loop yourself, you delegate the work to some object method, passing it a code block that will have to be executed at every passages in the loop. The method will have to make use of the yield keyword in order to call the block that has been passed to it. I wrote an article about code blocks in case you would like to know in more depth what I think of them.

2) Writing conditionals never been that exciting

What is more boring than writing a traditional if-then-else condition? Well, a lot of things in fact. But writing a “if” is still boring… a little… I think. In Ruby, you can decide to put the conditional keyword either before or AFTER the tested expression. It may seems like useless, but I personally think it helps to improve the code clarity in some situations.
For example, instead of writing a statement like this :

if(won_fight)
  puts "Yay!"
end

You could also write :

puts "Yay!" if(won_fight)

I love it. But wait there is more! Everyone knows about the if keyword, but not everyone knows about the unless keyword. It’s pretty straightforward so I’ll just write an example and you’ll understand.

dance_like_an_idiot unless struck_by_lightning

I personally like this last use of the unless keyword. In this particular case, I really wanted to put the emphasis on the idiotic dance while not bothering too much about the insignificant exception that follows. It all depends of the situation. Sometimes, the thing to do deserves more attention and some other times it’s the condition that matters the most. It’s only a question of personal taste, but it’s a nice touch nonetheless.
Note that there are other keywords you can place before and after the tested expression, like until and while.

3) You know you are addicted to OOP

With Ruby, everything is wrapped into objects, not only complex structures but native types as well. For example, String is not a keyword, it is the name of a ruby class. String contains methods that manipulates the internal string value. So instead of writing something like Uppercase(“blablabla”), you will write “blablabla”.capitalize. Instead of writing round(a_number) you will write a_number.round(). In short, there are less global keywords and more encapsulated methods. If you love OOP, I don’t have to convince you, I’m sure you’re already turned on.

4) Adopt a dynamic language today

Dynamic typing is wonderful and really should be taken seriously. You waste a lot of time declaring and giving a type to each of your variables in your statically typed language. Why not let an interpreter decides what kind of variable x really is only when you start putting some kind of value in it? It’s silly to say that dynamically typed languages are less serious than statically ones. When a programmer decides to create a variable in ruby, python or PHP, he will use it the proper way. He won’t put a number in variable x and later try to retrieves a date from it. Also, declaring variables takes more place in your code as well as more time in your life… and it’s just boring. Call me a hippie if you want, but I prefer a language that slacks off on types a little rather than one who points a gun at my head forcing me to code a certain way and trying to control everything.

5) Be part of a more underground community

Ruby isn’t the most popular language and shouldn’t be. Sure, It’s popularity is growing a lot recently and that is a great thing, i don’t say otherwise… but too much popularity and Ruby would lose some of it’s appeal. It’s just a special feeling to be part of a community that is a bit smaller and more underground. Small communities = more devoted people.

6) Rails

I just couldn’t pass aside Ruby’s best friend. When Rails arrived and revolutionized the web community, Ruby finally started to get some of it’s well deserved credit. Developing a web application with Rails is extremely fun and fast… and I’m not saying fast in the bad sense of the word. With Rails, you code less and you code better. Thanks in part to the MVC architecture but also to the greatness of the language hiding behind the powerful framework. Ruby and Rails forms a devastating combination. Ruby and rails convinced me that programming could be fun again… something I didn’t have anymore when I was developing in .NET (Yaaaaaaaaawn!).
There are tons of other reasons to try ruby. Could you give me a few?