Rubyize this

It’s not a secret, Ruby syntax offers many possibilities. One thing I enjoy doing once in a while is to take some code I have written a few days before and improve it to make it look more rubyish (read : short, expressive and readable).
I thought it could be fun to make a little game out of it. I’ll put a chunk of code that needs some improvement. Try to analyze and rubyize it.
Be warned though, the code snippet of today is quite stupid. It has been written by Fleebie, the red slime with a trumpet piston shaped mouth.

def manage_ducks(ducks)
  if ducks == nil
    ducks = fetch_some_champions
  else
    unless ducks.won_stanley_cup?
      ducks = fetch_some_champions
    end
  end
  ducks.beat_random_opponent
end

That’s it. How would you rubyize this piece of code?
#UPDATE : It seems that the PRE tag tip I talked about doesn’t work. WordPress strips the pre tags when you are not an administrator. I may have to hack some php files to make it work. Someone knows a wordpress plugin that let the users write nice and indented code snippets?

Our latest project TimmyOnTime now in alpha version!

Dan and I are extremely excited to release the alpha version of our new project called TimmyOnTime.
What is TimmyOnTime?
TimmyOnTime is a IM-based time management tool. To use it, you only need a Jabber client like Google Talk or Gaim (MSN or AIM users don’t despair! We also added support for these 2 networks). To have Timmy track the time on your projects, you only have to chat with him via your IM! Let’s say for example you want to create the following new project : Achieve hapiness. Well, you just tell Timmy about it and you write : create project achieve hapiness
Timmy will create your project and tell you if everything went OK in the process. Now that you have a project, you might want to create some tasks? Nothing is easier : create task smile more often
At this point, Timmy have started the first session on your new task. To stop the timer, just write : stop
Web access is optional
That’s right. One of the important thing for Dan and me was to make optional the web registration process. So, if you don’t want to bother about the website, just use your IM and chat with Timmy. However, we’re pretty sure you’ll want the added features of a web access (project / task renaming, time editing, etc).
It’s your chance!
We want to offer to RubyFleebie and JavascriptKata readers the chance to try this brand new application first. Since it is an Alpha release, we decided to limit to 150 the number of users that can access TimmyOnTime. If everything goes smoothly, we will increase that number slowly over time.
During this alpha period, we would appreciate that you give us feedback on the application. Also, if you find bugs, it would be nice that you let us know! ([email protected])
To get you started : TimmyOnTime

Ruby and Code Consistency

You know what is the one thing everybody will tell you if you ask them about the ruby programming language? They will tell you that everything is an object, bolding the “everything” like I just did. I think every rubyists in the world said this sentence at least once in their life. After telling you that everything is an object, they will probably tell you about code blocks, ducktyping or whatever cool feature ruby has to offer (that’s what I did). And finally, they will tell you that ruby gives you several ways to achieve a single thing.
This is great, I mean, this is really great. Ruby lets you express yourself, how nice is that? But that delightful feeling of freedom comes with one responsibility : you have to keep your code consistent.
Sure, you can go all funky and do that :

if(var == "xyz")
  var2 = "hohoho" unless x || y
  unless var3
    #do something on a single line
  end
  a_collection.each do |item|
    puts item
  end
  another_collection.each { |item|
    puts item
  }
  do_something if !x
  do_something_else unless y
end

It works! But God… where is the consistency?

  1. On line 1, parenthesis. On line 4, no parenthesis? Hey!!
  2. Line 2 : Those great modifiers… perfect for some clean one liners! Line #4 : Why no modifier this time?
  3. Line 8 : You enjoy using do and end for your blocks? Cool! Line 12 : Hmm, now you’re using those braces just to confuse the hell out of me? The convention I use (i don’t know if it’s official or not but I read it somewhere) is to write “do” and “end” when the block takes more than one line of code. Otherwise I use braces and put the whole expression on a single line, like that : my_collection.each {|item| puts item}. But whatever your preference, the important is to stick with a convention.
  4. Line 16 : The if modifier is used in conjunction with the ! operator. Line 17 : unless modifier is used.

This kind of things won’t break your code, that’s for sure, but inconsistency is bad because it makes our applications look more random, more chaotic.
With ruby, it is so easy to write anything the way we want at the moment we are writing it. I admit I do it sometime. However, we… must… resist…
Pick a style
Recently, I began to create my own conventions. I will put some of them here just as an example. What’s important here isn’t the conventions per se, but the fact that I do my best to follow them.

  1. “unless” over “if !”
  2. Indentation : two white spaces
  3. if operation precedence isn’t an issue, no parenthesis
  4. Blocks : “do” and “end” if more than a line, “{” and “}” otherwise
  5. At the end of a function, no use of the “return” keyword (e.g. obj instead of return obj)
  6. Whenever possible, no “global” looping. In other words : “collection.each do |item|” over “for item in collection…”
  7. String concatenation : << over += (and it's more efficient!)

There are a lot more… but I don’t see the point of writing them all.
What are your conventions? How important is it for you to be consistent in your code?

Playing with blocks : Part 2

In the first part, I tried to cover the basics of code blocks. Now, we’re going to talk about : Code blocks and scope
A code block is a closure
Oh no… not another definition of a closure? Yes, but I promise I will be quick. First, to understand what a closure is we have to understand what a scope is. A scope is a region of your code where the variables share the same life cycle. You can’t access the components that are located inside a given scope when you’re out of it. For example, when you write a method, every local variables you define are located in the same scope. The outside world can’t access them because these local variables are living in another execution context (scope) and they only exist for a short period of time. When the interpreter is done executing the method, its scope is destroyed by the garbage collector.
A closure is a collection of 1 or more lines of code that has it’s own scope attached to it and that is defined inside the body of a method. What makes a closure a closure is that it keeps its own scope when the outer method has finished executing. More than that, the closure will still have access to the scope above, that is, the scope of the method where the closure was defined (the outer method). With closures, scopes that normally would have been destroyed see their lives extended.
So :

  1. A closure has it’s own scope
  2. A closure is defined inside the body of a method (that’s another scope)
  3. A closure has the power to extend the normal life of these 2 scopes
  4. A code block is a closure

But to be a real closure, a code block must be stored in a Proc object. Why? Because if you pass a block to a method and that this method invokes it with yield immediately without storing it anywhere, everything will stay “in scope” from the beginning to the end. That’s quite a boring closure if you ask me (but it’s still the only thing we need most of the time). When I think of a closure, I don’t want to think of something volatile like that, I want to think of something persistent … something that will live as long as I want.
Here is a small example I wrote to clear this out :

class ScopeTest
  def defining_the_block
    outer_scope_var = "hello!"
    @proc_object = Proc.new {puts outer_scope_var} #we store the closure for future use
  end
  def calling_the_block
    @proc_object.call
  end
  def test_it_all
    defining_the_block
    # ... Thousands of lines of code here
    # more lines of code
    # Oh! God! I forgot about that block I have defined earlier! I wonder if it is
    # still alive. (TODO : Stop writing dumbass comments in production code)
    calling_the_block #output => hello!
  end
end

As you can see, storing the block inside the @proc_object instance variable kept its scope from being wiped out by the garbage collector. It did also preserved the scope of the outer method defining_the_block, that’s why the local variable outer_scope_var was still alive and accessible by the closure at the very end of the listing. Without the existence of the closure, that variable would have been destroyed at the end of defining_the_block.
I’ll stop right there. In the first part I said I would talk about lambdas… I lied, sorry. I thought it was spelled lambada, that’s why I was very excited to write about this very hot dance from Brazil. Once I learned that it was spelled lambda, it just turned me off.
I got you… believe it or not this isn’t the real reason! The real reason I’m not writing about lambdas is because I think the article is long enough. Maybe in the next part, if there is one, I’ll write about them.

Finally, the answer to the question "What is Fleebie?"

First of all, those who read this in a feed reader should click on the link to see the new face lift that happened to this blog. Personally, I love it. I’d like to hear your comments on that.
A lot of people asked me : “What is a Fleebie?” or “Who is Fleebie?”. I always tried to hide the truth to my readers, telling them it was only a word without meaning. It worked for a while, but now I can’t lie to you anymore. You all deserve better than that.
Fleebie is the little red thing you see at the bottom of every posts. It is a strange little alien that is kind enough to teach me the ruby programming language. The articles you find here are thought by Fleebie. My only job is to write what the red alien is thinking. It is NOT an imaginary friend of mine… or at least it shouldn’t be. You can see it right?
Anyway, just wanted to introduce Fleebie to you. I’d like to let you know that whenever I write something irrelevant or confusing, it is its fault.
The new design is the work of Alex Dumas, who is just a tremendous web designer as well as a good friend of mine. Thanks Alex! This new design is rocking hard.
UPDATE!
The comments are working now! Sorry about that…