Syntactical Sugar: conditionals

jd / Mon, 05 Mar 2007 19:19:00 GMT

Tags ,  | 3 comments

This article has moved over to our sister spin-off blog, RubyJudo, which focuses on more arcane technical topics than NotRocketSurgery.

Comments / Leave a response

  • kit said about 12 hours later:

    Yes I would say I use that last syntax quite a bit. If the expressions are simple, it ends up looking better. If you have multiple branches (else if) or if the expressions are complicated in any way, it could get ugly.

    Speaking of which, does ruby code end up in smaller, more manageable chunks, from smaller methods to less complex expressions, all on its own, or is it just me?

  • JD said about 24 hours later:

    Yes, if the condition is complicated, then a 3+ line block make sense. For multi-line conditionals, I bring back use of the then keyword for readability as well:

    if @foo.bar? && @foo.foo? && @foo.moo? ||
       (@foo.new_record? && @foo.name == 'bar')
    then
      @foo.horrible_example = true
    end

    To some degree, Ruby helps keep your code simple. I think this is because you have more direct tools to accomplish what you need to do, like blocks and methods like #collect and #inject. However, keeping your code comprehendible often takes conscious effort—in other words, I’ve still seen some pretty badly written Rails code.

(leave url/email »)

   Comment Markup Help