10 Reasons to Learn Ruby

Ten possible reasons to learn the Ruby Programming Language

Preamble

I discovered Ruby fairly recently, through the excellent Ruby on Rails framework1. Although I don’t consider myself a Ruby expert by any means, I read the PickAxe2, I’ve coded a few utilities for my personal use in Ruby and I’m currently developing with Rails during my free time.

Ruby is currently my programming language of choice; I started off with Turbo Pascal in high school, discovered C and C++ at university, did my thesis in Java and learned PHP from scratch because I wanted to learn how to make websites quickly and easily. I guess I feel compelled to code sometimes, more as a form of entertainment than anything else. Rather dissatisfied with what I tried language-wise, I was determined to start learning either Python or Ruby. I chose the latter because I didn’t want incorrect indentation to break my code3, and here I am, heaping praise upon it.

There are plenty4 of introductions, tutorials, articles and essays of different sorts which aim to guide the novice and advise the guru on how to get the most out of Ruby. This article, however, is not one of them.

It’s more of a modest, humble, and incomplete list of a few reasons which may (or may not) entice you to use Ruby or at least play with it a bit. A word of caution: if you are using another programming language for work or whatever, don’t complain to me if you don’t want to use it anymore – that’s exactly what happened to me, but luckily, it didn’t matter. Ruby is a very beautiful and elegant language, but like all things of this sort, it may well poison your mind and corrupt your soul…

You have been warned.
h3. Why learn Ruby?

#1 – You get all the treats without the tricks

Ruby borrows from all the best programming languages out there, from smalltalk to Java, Perl to Python5. Basically, here’s the features and functionalities Ruby gives you which you may have seen elsewhere:

  • Exceptions: Believe it or not, exceptions are one of the most important things to master when developing any kind of application. PHP4 programmers probably won’t know anything about them and they’ll tell you to just print stuff on the screen or use their “extremely advanced” class for error handling. Please, ignore them. Fortunately for all of us, Ruby comes with try/catch (or better, begin/rescue) blocks and a series of predefined, extensible Exceptions to handle errors properly.
  • Namespaces: Ruby modules make excellent and easy-to-use namespaces, for the joy of Java and C++ enthusiasts.
  • Built-in Regular Expressions: For all the Perl monkeys, you can put something between slashes and it will become a regular expression, ready to be matched with a =~ operator.
  • Overloadable operators: Ruby lets you define operators like +, -, etc., for any of your classes.
  • Packages: Called “gems”, they really are solid and precious indeed…and they work! Packages support dependencies, and they can be either cross-platform or platform-dependent.
  • Interactive Shell: the Interactive Ruby Shell can be used to test Ruby code instantly, similar to the Python console.
  • Unit Testing: The Test::Unit module makes things so easy that you really don’t have any excuse not to test your code.

#2 – You’ll love the little things

Ruby is elegant. Why’s that? Because it doesn’t focus on making code concise so much as readable and usable. Here are some tips to help you out:

  • You can use both if and unless in condition statements. Of course you can just use if and negate the condition, but unless can be less error-prone at times. Furthermore, you can use both operators as conditional modifiers, after a statement rather than before: order.new unless order.exists.
  • You can use question marks and exclamation marks at the end of your methods. Although no convention is enforced, ? is added if the method should return true or false, while ! is used to clarify that the method does something forcefully, like destroying a database record, chopping off the last character of a string, etc.
  • You can use the alias directives to create an alias for a method already defined. In this way you can have an exist and an exists method at no additional cost or repetition.
  • You can use the attr_reader, attr_writer or attr_accessor directives to automatically generate getter and setter methods for specified class members.
  • Some naming conventions are enforced for your own sanity: constants, classes and modules are capitalized, methods and members must start with a lowercase letter; global variables are prepended by a $, instance variables by @ and class variables by @@; etc.
  • Parentheses are optional in method calls. You can therefore write File.open(“/home/h3rald/test.txt”) or simply File.open “/home/h3rald/test.txt”, which is particularly handy with methods that don’t take parameters.

#3 – You won’t ever use a semicolon again

You want to add another instruction? Just go on the next line. Hit and you’re done. In Ruby, like in Python, newlines matter and you don’t have to remember to end your instructions with a semicolon. Unfortunately this means that you won’t be able to write your whole program in a single line of code, like the C++ folks… that’s too bad, isn’t it?

UPDATE: Indeed you CAN use semicolons as line delimiters in Ruby as well, the point, however, is that you don’t have to.

#4 – Everything is an object, as it should be

When I studied Java they taught me that everything is an object.

- “So 14 and 374346.678 are objects then?”
- “No, silly, they are numbers!”

In Ruby, numbers, strings, Boolean values et al are objects. Really. This means you’ll write things like:

"YOU SHOULDN'T ALWAYS USE CAPITALS".downcase #=> outputs "you shouldn't always use capitals"
-12.abs #=> outputs 12

instead of something like:

# PHP Code

strtolower("YOU SHOULDN'T ALWAYS USE CAPITALS");
abs(-12);

You save time, you save brackets, and it just makes more sense.

#5 – Everything has a value

Or “you’ll hardly ever use return to return values”. In a nutshell, all Ruby instructions return a value, even variable assignments, so you don’t really need to use the “return” keyword at the end of a method; the value of the last assignment or any other expression will always be returned.

#6 – You can alter your environment in any way you like

The first time I saw this, it really freaked me out. Imagine a typical programming situation: you start using a system class or a class written by someone else and you notice that you’d like to have an additional method. At this point you have a few ways to handle this in ordinary programming languages:
s

  • You modify the developer’s source code, if you have access to it. This is normally not a good idea, and you shouldn’t do it.
  • You derive a new class from the original one, and you implement the new method there. This is a good idea, but it could be overkill for just one method, and you may have to update some of your other code accordingly.
  • You give up, and you just create the method outside the class, somewhere else. This can be done, but it is not very elegant and goes against Object Oriented Programming.

In Ruby, you can simply add the method to the original class, without having to hack the original source code, and even for system classes! You want to have a method to automatically convert a measurement from meters to feet? You can simply extend the Numeric class as follows:

class Numeric
  def feet
	self*3.2808399
  end
end

From now on, all your numbers will have a feet method, which can be used just like any other method that was originally defined for the class:

5.feet #=> Returns 16.4041995

Basically, Ruby classes are never closed and can be modified at any time from anywhere. Use with care, of course.

#7 You won’t get unicorns from birds and horses, but you’ll still get donkeys if you want

I distinctly remember my C++ professor at university using animals to illustrate key object-oriented concepts like classes and inheritance. Weird things came in when she tried to explain multiple inheritance to inherit a class Pegasus from a class Bird and a class Horse. It had methods like “fly” and “neigh”… crazy stuff, anyhow, Ruby does not offer multiple inheritance.
This seems to be the trend, after all, and of course it’s up to tastes. I don’t quite fancy multiple inheritances, as they may lead to unpredictable things. Nevertheless, it is possible to create “mix-ins” using Ruby modules, so that members and methods defined in a module will be added to a particular class if the module is included in it.

#8 You don’t really need XML

XML is a nice, general-purpose markup language which can be processed by every programming language and used everywhere. Unfortunately, it can also be quite verbose to write, very difficult to parse, and let’s be honest, it’s not really readable at first glance in many cases, unlike the following code snippet:

regexp: !ruby/regexp /a-zA-Z/
number: 4.7
string: a string

This is definitely easier and more readable than XML, isn’t it? Welcome to YAML, Ruby’s favorite markup (but not really6) language, which can be used to represent any Ruby object in a simple, clear and yet complete way.
Ruby can parse XML, but YAML’s simplicity convinced a lot of developers to use it as an alternative to XML for configuration files, for example (Rails does this).
The code snipped presented before was obtained by executing the following line of Ruby code:

{"string" => "a string", "number" => 4.7, "regexp" => /a-zA-Z/}.to_yaml

The to_yaml method is defined for the Object class, which is the father of all of the other classes, and thus it is available in all Ruby objects. This means that you can convert anything into YAML and re-convert anything back into Ruby objects, with total transparency for the developer. So much for parsing, huh?

#9 Lambda is much more than a Greek letter

Ruby borrows some magic from Lisp and Perl with Proc objects and blocks. Procs are _"blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables." _7 Consider the following:

def gen_times(factor)
	 return Proc.new {|n| n*factor }
   end

   times3 = gen_times(3)
   times5 = gen_times(5)

   times3.call(12)               #=> 36
   times5.call(5)                #=> 25
   times3.call(times5.call(4))   #=> 60

I could have used the lambda method instead of Proc.new and gotten the same result. This should ring a bell for people who know Perl and Python (or Lisp)8. You can do the same thing in PHP as well, but most people don’t really use the function.9

Additionally, Ruby makes extensive use of blocks, sort of “unborn Procs”10, for example, to iterate the contents of an object and execute some code, like the each method available for the Array class:

[1, 2, 4, 6, 8].each {|c| puts c*2} #=> outputs each element multiplied by 2 in a new line.

Should the code in the block exceed one line, you’re advised (but not required) to include the block within do … end instead of using braces. Ruby folks don’t like braces much, really.

#10 – You can go on Rails

Last but not least, you can always use Ruby on Rails for developing web applications. Deployment may not be as easy as it is with PHP, but Rails was built in Ruby because Ruby has features no other language can offer.

Conclusion

Time’s up. You’ve probably made up your mind about Ruby already, and you are either playing with it already, or you’re totally ignoring it. However, the next time you’re frustrated because your code looks ugly and you think you could have done the same thing with half the code you got, don’t blame me!

Notes

1 Ruby on Rails, MVC Web Development Framework.

2 Programming Ruby, by Dave Thomas & others, Pragmatic Programmers, 2004

3 Not entirely correct, but sort of. For more information on Python’s indentation rules and myths, read Python: Myths about Indentation.

4 For a list of Ruby tutorials, refer to the Documentation section of the Official Ruby Website.

5 For more information on Ruby, and in particular on the similarities and differences with other languages, refer to Ruby from Other Languages.

6 YAML is Not a Markup Language.

7 Definition and example taken from the official Ruby documentation for class Proc.

8 For some example on lambda functions in Python, see Python: Lambda Functions.

9 For examples of “lambda functions” in PHP using create_function(), see this.

10 For more detailed information on Ruby’s Procs, blocks etc. refer to Understanding Ruby blocks, Procs and methods.

Legacy Comments

These comments were imported automatically from an old version of this web site. Scroll down for the newest stuff.

Great article! It just explains perfectly why Ruby is starting to take over my life. And why Rails makes CakePHP look like a very weak wannabe. But I don’t blame Cake (I use it every day); it’s PHP’s fault.

No mention of maintenance or testing?

Now you have learnt Ruby, would you defend being able to write code where the indentation is contrary to the code structure?

- Paddy.

@Joel: Glad you discovered Ruby! Good luck!

@Paddy: You’re right. I should have mentioned at least testing. I updated the article (Reason #1) to at least mention Test::Unit. And yes, as a matter of fact since I’ve been using Ruby my code indentation definitely makes more sense. You seem to be a Python enthusiast, from your site at least: sorry about the silly remark about Python’s indentation in my article… I just couldn’t resist (but I did added an interesting note about Python’s indentation in the notes too).

Chris

Thanks so much for this. I’ve been teaching myself to program for several months now with Ruby, and this very much helped me put things I’ve learned into context.

Very nice writeup. I totally agree.

There’s only one thing I really hate about Ruby: it made me realize how bad the other languages are and took a lot of fun out of the “normal” software development.

Right now I have to code PHP (BTW, Joel is 100% correct, CakePHP is a pretty good framework and makes working with PHP bearable) and more than a few times every day I would like to puke because the language sucks.

Masklinn

> Interactive Shell: the Interactive Ruby Shell can be used to test Ruby code instantly, similar to the Python console. Similar, but much much worse. The Python consoles (both CLI launched by typing “python” and the IDLE environment) are more flexible, more practical and much less annoying than IRB (I suppose that’s what you were talking about) > Unfortunately this means that you won’t be able to write your whole program in a single line of code, like the C++ folks – that’ss too bad, isn’t it? In reality, you can. The statement terminator (in both Ruby and Python) is either a newline or “;”. So you can write your whole Ruby program on a single line, I think (you’d need to use parens to define functions, but it can be done. > Everything is an object, as it should be I think you should use examples with things that aren’t objects in “popular” languages, such as integers or booleans, or even ‘nil’. Strings aren’t object in PHP because PHP barely has objects, so it’s not really fair. > Everything has a value You should emphasize that point by showing that e.g. if/else blocks return a value. > the value of the last assignment will always be returned. Didn’t you mean “the last value evaluated” or “the value of the last expression”? Because you definitely aren’t limited to assignments. > You can do the same thing in PHP as well, but most people don’t really use the function. Because it’s ugly, hackish, and since you create functions by providing strings there is no syntax checking before runtime itself.

@Masklinn: Thanks a lot for your comment. I updated the article where necessary!

Kookoolen

Nice article.

For feature #4, you should add that even nil is an object. Try nil.to_i for example.

Moreover you can open NilClass and add your own methods ! Rails does so to add debugging information when you called a method on nil.

Hi,

Nice and happy to see your 10 Reasons added to 10 another advantages on a blog that is based on IronRuby.

The Author claims 10 + 10 Advantages as 100 rather tan 20.

Happy Reading there.

FlySwat

So ruby has all of the features that C# has, except that its slower.

Cool!

Shantanu

Have you taken a look at Scala, or Erlang?

Correction for #8:

The syntax for hash initializers is

{ :key1 => value1, :key2 => value2, … }

(‘=>’ instead of just ‘=’)

@Shantanu: I am now, they sound interesting actually.

@Steffen: You’re 100% right. This was due to the fact that I accidentally stripped all the > symbols out of the article when I converted it from BBCode to Textile. Thanks!

Erik Ordway

The thing that everyone always seems to forget about XML is that it was never meant to be read/written buy humans. It was and is meant to be a cross language/platform transport methodology. It is easy process on each end without having to dealt with things like big and small endingness , line feed and carriage returns in files, and crap like that. The core of it is that if you personally are reading or writing XML then you are doing something wrong. Ant on java being a classic exampl, it was not even valid xml.
All that said I love Ruby too.

日,我都看不懂

jim

And make sure to read through resources such as http://snippets.dzone.com/tag/ruby as well. A real time saver from time to time!

wayne

我了解ruby,但是看完后我决定开始学习ruby

Very interesting — makes me more interested in Ruby than I’ve ever been.

BTW, your PHP number example is missing semicolons.

wefwefwef

10 reasons to NOT learn ruby:

1. It’s Shit
2. It’s Shit
3. It’s Shit
4. It’s Shit
5. It’s Shit
6. It’s Shit
7. It’s Shit
8. It’s Shit
9. It’s Shit
10. It’s Shit

Anders Persson

Still Java and C# have nice built-in GUI handling, and i don’t have to download a lot of package like TCL/TK.
Ok Ruby like other language is nice, but for people like me that have to develop GUI-apps from time to time Java and C# still is my choice.

I was looking into Ruby, and it is nice but…
Maby the language expands in the future.

Anon

Do I smell Blub programmers in the previous two comments?

Anders Persson

Hmm start to get old, i don’t know what a Blub is,
But i guess it some one don’t like eg Ruby.
I can’t talk for others, just for me.
I like the syntax, and the language
I have written a script to build my company software on Windows, looked a Perl as i have worked with before but thout that i could be nice to test Ruby, and it did a great jobb, easy to read etc.
But to start using it as regular no 1 language i still missing easy GUI stuff like in Java.
Maby you thing i am a “Blub” if so okej a put it on my card smile
// Anders

Fielding Feng

10 reasons that describe in this article are either already exist in Java, or not very useful to me. Except the unless condition.

toby

Python, en, i like it.
Ruby, nothing

good list, but a detail: lambda is a method, not a keyword :)
>> Kernel.method :lambda
=> #

el_vartauy

good list, but… why if you don’t like the python indentation problems, you prefer yaml over xml?
i think a handy built in method is not enough?
good luck!

http://prayas.blogvis.com/

liked your article and visitors arguments.
Ruby rockssssss.

kraig

ruby is so cool, i love it as well!

To those bashing Ruby without giving real reasons: you’re not really accomplishing anything by posting.

@el_vartauy YAML is especially good for configuration files because it makes it really easy to edit/read. As for using XML or YAML for data transfer, you’re actually probably better off using JSON because XML tends to be larger in byte size and YAML isn’t as supported as JSON or XML. And you should note that even Google, software engineer giant, decided XML wasn’t right for their usage and developed Protocol Buffers (and recently open sourced it).

@Masklinn More of a question than anything: What are the annoyances of IRB that Python interactive console lacks?

alan

@flyswat: so C# has all the features of C++, except that its slower. Since you’re probably a microsharft fan, try ironruby and get essentially the same speed.

@fabio: you can do ruby deployment as easily as php deployment with phusion passenger.

Nice article, it summarizes many of the things that I use in everyday work.

I’d suggest covering the Range class and the methods in Enumerable (such as each/map/select/inject/find/sort). Maybe talk about the other cool things you can do with blocks (aka closures). These tools have made solving projecteuler.net problems a cake walk.

5.times { puts “oooh yeah” }

5.downto(0) { |i|
puts “t – #{i} minutes, until launch”
sleep 60
}

(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(1..10).map { |i| i * i }
=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

(1..10).select { |i| i % 2 == 0 }
=> [2, 4, 6, 8, 10]

(1..100).inject { |sum,i| sum + i }
=> 5050

(1..1000).to_a.reverse.find { |i| i % 11 == 0}
=> 990

Also, might want to give a shout-out to Ruby 1.9.1, which is due to be released in 1.5 months. I’m currently using Ruby 1.9.1-preview1 for projecteuler.net stuff, it’s byte-code VM is quite fast.

As for the other comments that I noticed, it appears that other languages have some angry trolls. Not a language/community feature I’m really interested in.