The Challenge of Learning Ruby

One of the biggest challenges I have as a Perl programmer is dealing with the change in the underlying language that Rails is written in, namely, Ruby.  To help with this I’m working myself through Project Euler to do a couple of things

  • Force myself to work through problems in Ruby
  • After solving the problems, see how others did them

The last item is the most important.  I generally start off in a very perl-ish, procedural way.  When the answer arrives it’s a real eye opener to see how others solve the issues.  For example, for one problem after solving it in what I thought was a fairly elegant way (a couple of short functions), seeing the first Ruby based solution in the forums the programmer had used a quick Monkey Patch (modification of the base Integer class in this case) to simply add a function that did what he wanted.  I had never even thought of this!  I knew the capabilities of Ruby to do this, but my brain just hadn’t triggered the idea that this was a good solution.

The pros and cons of Monkey Patching are a discussion for another day of course :)

I’m fairly proud of myself, I have worked through some of the problems and even just wrote the following line of code… on purpose!

(1..100).inject { |s,i| s*i }.to_s.split(//).inject(0) { |s,n| s + n.to_i }

I admit that my perl-ish nature of doing it all on one line came out a bit :) The actual solution that I came up with was a bit nicer of course!