First steps with Ruby – from a C# guy

As it seems very likely that my first ThoughtWorks project will be a Ruby project, I have been spending as much time as possible getting up to speed.  After getting HomeBrew and the latest Ruby version installed (this was more painful than I would care to admit) I worked through the first 25 problems on Project Euler.  This really is an excellent way to practice using a new language – plus it’s quite fun.

I’ve found the biggest problem for me is that I end up writing C# in Ruby – I’m writing Ruby code, but I’m using all the techniques I’m used to in C#.  I think it will probably take quite a while to change this.

Today I’m going to take a look at a few surprising features in Ruby.  This is super beginner stuff, but it was pretty new to me.

Multiple Variable assignment

Let’s say you have a string containing 2 numbers, separated by a space, and you want to extract those 2 numbers.  (This is actually something I did quite a few times in the Project Euler problems)  Coming from C#, I’m used to doing something like this.

input = "12 13"
splits = input.split(" ")
a = splits[0]
b = splits[1]

Which is correct, but we can do much better.

input = "12 13"
a, b = input.split(/\s+/)

The result of the split method is an array, but Ruby allows us to assign the result to 2 variables.  Here I’m also using Ruby’s built-in support for Regex.

Shift operator

Another example – let’s say we wanted to fill an array with with all multiples of 3 below 100.  I might do something like this.

res = [] 
(1..100).each do |i|  
    if i % 3 == 0    

(The use of the push method is probably from me being used to JavaScript)  Again, this is correct, but we can do better.

res = [] 
(1..100).each do |i|  
    res << i if i % 3 == 0 

Here I’m also using the if statement as a modifier.  (This is actually one of my favorite Ruby features)

Automatic number conversion

If you’re working with big numbers in C#, you probably need to go through your code and change int to long everywhere.  Or you need to manually convert between the types to avoid overflows.  Quick – what’s the upper limit for the Integer class?  That’s right, keeping track of number limits is annoying – luckily Ruby agrees.

Take a look at the following code.

num = 716.times do    
    puts "#{num.class}: #{num}"    
    num **= 2

Here’s the result:

Fixnum: 71
Fixnum: 5041
Fixnum: 25411681
Fixnum: 645753531245761
Bignum: 416997623116370028124580469121
Bignum: 173887017684702179246328390437079448141248104062408434512641

Like I said, anyone who has done any amount of Ruby is probably looking at this as beginner stuff (which it is), but coming from a C# background – it’s pretty awesome.  Happy coding.