Main Content

Ruby v Perl - a comparison example

Archive - Originally posted on "The Horse's Mouth" - 2012-02-21 23:29:22 - Graham Ellis

One of the popular exercises I set on our Perl courses goes something like ...

Write a program to ask the user to enter four numbers each between the value of 1 and 6. If the user enters a number below 1 or over 6, ask him to enter that number again. If the user enters the word END, stop reading numbers.

Print out the count, average and total of all the numbers entered. Take care to print an appropriate error message for the average if no numbers were entered.

and I then add Please try to do the following exercise WITHOUT using the words "while" or "if" in your program. which encourages the use of a for loop, lazy operators, and constructs such as unless and ? ... :, even though in real life you would use at lead one if for this task.

I set the same exercise in Ruby earlier today - unusually, this week's group is not converting from another language such as Perl where such constructs are familiar - they've done a little C and Java, where the options are limited and I wanted to gently encourage them to try these new and powerful facilities. Sample program - [here] and a comparative example in Perl [here].

What do I notice as I look at the two programs? A remarkable similarity in the concepts. A simplification in Ruby in terms of not having to think if I'm comparing strings and numbers, but a need in Ruby to convert with .to_s and .to_i methods. The lack of $ on local variable names in Ruby, which means that I can't just drop a variable into a string to output it - I need to use #{...}. And the use of methods in Ruby such as .chomp as it's so much an object oriented language. With all those changes, every single line of code is different ...

If you want to learn Perl, take a look at our Perl Courses. If you want to learn Ruby, take a look at our Ruby Courses. In both cases, we've options to help you learn whether you've never programmed before, if you're experinced in one of the pair and converting, or - as is more usual - if you're somewhere between.