10 Ruby programming tips you should already know

Other blogs about Ruby or Rails have already touched some of the tips I’m going to show, but it never hurts to remind you these small recipes aimed at Ruby novices:

  1. Default method parameters as a hash:
    I tend to use this when the argument list tends to vary, and I want to have a couple of nice defaults for the method attributes. This is actually what Rails uses intensively.

    def my_method(my_default_attributes={}) default_values = {:name=>”Anonymous”, :race=>”elf”, :age=>13}.merge! my_default_attributes … end

  2. Store results in instance variables:
    Let’s say I’ll invoke many times a method that returns the sum of elements in a list that’s an instance variable. I wouldn’t want the calculus to happen every single time I call it, but will store the result in an instance variable, like this:

    def my_compute_stuff unless @my_compute_stuff_local_var @my_compute_stuff_local_var = 0 … # extra computation that stores the result into @my_compute_stuff_local_var end return @my_compute_stuff_local_var end

Even better, when the computation in question is a one-liner, we can condense this to:

  def my_compute_stuff
    @my_compute_stuff_local_var||=... # the extra computation that stores the result into @my_compute_stuff_local_var

What if we want to force the recompute?
I’d use:

  def my_compute_stuff(force=false)
    if !@my_compute_stuff_local_var or force
      @my_compute_stuff_local_var = 0
    return @my_compute_stuff_local_var
  1. Comment out several lines at a time
    When I want to comment a block of several lines, I use one of two tricks:
    a. I use Textmate (on Mac) with the multi-line insertion; that is, I go to the start of the first line I want to comment, click, press Alt(Option) so that the cursor turns into a cross, click at the start of the last line and press #; all the lines from the first to the last get commented out simultaneously
    b. Ruby’s less known block comment syntax (see also here):

         We're in a comment here.  Both the =begin and the =end must be the  
         first elements on a line for this to work.
  2. Multi assignment
    Like other dynamic languages, Ruby also allows assigning several variables at a time, like in this example. The secret behind the magic trick is that Ruby will consider both the left and the right side as arrays. Which also leads to tip number 5.

         b, c = 5, 6
         a, b = b, c
  3. Multiple return values
    Your method wants to return several things at the same time, this is magically taken care of by the multi assignment:

       def sum_dif(a, b)
         return a+b, a-b
       a, b = sum_dif(4, 5)
  4. Playing with dates
    Whenever I need to create a date, I usually create it using Date.civil(year, month, day). What if I want to find the date of the last day of the month?
    Date.civil(year, month, -1) is the answer.

For instance,

      a = Date.civil(2008, 06, -1)
      a.day # == 30
      b = Date.civil(2008, 02, -1)
      b.day # == 29
  1. Still about dates: nicely printing out a date is as simple as nicely reading it from a string:
    For instance,

    b = Date.strptime(“07/02/2008”,”%m/%d/%Y”) # b becomes the date of 2nd July 2008 b.strftime(“%d - %m - %Y”) # will print “02 - 07 - 2008”

  2. You surely already know this, but I love it anyways: a very nice well-known construct is to move, when possible the if condition at the end, turning a 3-liner into a one-liner:

       if my_condition
       # into 
       one_line_operation if my_condition
  3. Pretty print strings decimals. The format descriptors are pretty much similar to those used in C’s printf so I won’t go into details.

       my_string = "%01d %06d %02d" % [type, code, age]  
  4. Enumerable’s Inject method. This nice functional programming trick will shave quite a few lines of your code. For instance, the sum of the ages of your users (in the @users array) is computed as simply as doing:

      ages_sum = @users.inject(0) {|sum, user| sum + user.age }