Programming ≈ Fun

Written by Krešimir Bojčić

I Would Love to See This in Ruby

I like small methods. Small methods make comments unnecessary and allow me to describe algorithms in a way I will understand in couple of months when bug strikes. They allow me to develop domain and talk about domain in the code. There is just one thing bothering me:

The excessive presence of end keyword.
This is particularly bothersome for small methods.

def numbered?(line)
  line_numbering_style  == :all_lines || significant?(line)
end

def significant?(line)
  line_numbering_style == :significant_lines && !blank?(line)
end

def blank?(line)
  line.nil? ? false : line.chomp.empty?
end

def numerize(line, counter)
  counter.increment
  "%6d\t%s" % [counter.current, line]
end

This looks much better:

def numbered?(line)
  line_numbering_style  == :all_lines || significant?(line)

def significant?(line)
  line_numbering_style == :significant_lines && !blank?(line)

def blank?(line)
  line.nil? ? false : line.chomp.empty?

def numerize(line, counter)
  counter.increment
  "%6d\t%s" % [counter.current, line]
I am not talking about full blown Python indentation scheme.

Although it is working in haml just fine I hate counting spaces in the middle of method… I know this was talked about back in a day and the conclusion was that it’s not worthed. (I agree).

BUT I’ve noticed any time I write similar code in Clojure or Smalltalk I don’t get to write an end to the method. When I compare the results I always get the urge to write one liner in Ruby. It sort-of works for simple code (notice that there is no semicolon):

  def blank?(line) line.nil? ? false : line.chomp.empty? end

For anything bigger than that one liner makes it harder to read. For those cases when one liner is not cutting it I would even agree to put a dot at the end to ease things up for parser (if that helps):

  def numbered?(line)
    line_numbering_style  == :all_lines || significant?(line).

  def significant?(line)
    line_numbering_style == :significant_lines && !blank?(line).

  def blank?(line)
    line.nil? ? false : line.chomp.empty?.

  def numerize(line, counter)
    counter.increment
    "%6d\t%s" % [counter.current, line].

« Refactoring exercise Ruby Oddities »

Comments

Copyright © 2019 - Kresimir Bojcic (LinkedIn Profile)