What I love about Ruby

I talk about Ruby all the time, even being proficient with other languages (such as C, Java and C# – but not C++). Why is that? Well, Ruby has a lot of incredible features that you may find on other languages, but generally are not on static languages:

1 – Code blocks and lambdas

I talked a little about them in a previous post. While a lot (really, a lot) of languages have support for anonymous functions and closures, the “big ones” don’t*. And the way that Ruby implements that is so elegant that most newbies don’t even know they are using a closure, or what would be that.

Actually, C++ (since C++11) and C# (we could use delegates since C# 1.0, but it evolved until C# 3.0) have anonymous functions, and C can do something similar using pointer to functions. Java, on the other hand, doesn’t have anything similar (but everybody is hoping it to implement that on Java 8). But the way Ruby handles that is just so elegant. For example, I can easily select all the non-null entries of a given Array @array with:

non_nil = @array.select { |x| x != nil }

2 – Metaprogramming

Check this:

class Numeric
  def method_missing(m)
    time_hash = { "seconds" => 1, "minutes" => 60, "hours" => 3600 }
    if(time_hash.has_key? m.to_s)
      return self * time_hash[m.to_s]
    else
      super
    end
  end
end

Now I can use the methods “seconds”, “minutes” and “hours” in any numeric object, and with a really DRY code!

These methods are created at run-time, whenever they are needed. Ruby can do that. And it can do more (Rails uses a lot of metaprogramming on ActiveRecord). It’s a really big subject, and I could spend a lot of time talking about that.

3 – Open classes

Have you seen what I’ve done in the previous code? I changed the behavior of the Numeric class. I can do that with any class, have I created it or not. Even built-in classes can have its behavior subscribed.

Now, a lot of people won’t like that, and they have some reasons. And while they can be right sometimes, it is much better to simply change the behavior of a built-in class than to always use a child class on the whole application.

4 – The object model

Everything in Ruby is an object. And when I say everything, that’s everything. Even classes are objects (of the class Class). That means you can create and manipulate almost everything inside of Ruby in runtime.

There are other reasons for why I love Ruby, but these are the main ones.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s