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.
Which is correct, but we can do much better.
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.
(The use of the push method is probably from me being used to JavaScript) Again, this is correct, but we can do better.
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.
Here’s the result:
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.