Ruby Beauty – Optional Parentheses on Method Calls

April 8, 2010 • Damien White

Continuing with my exploration of Ruby as a .NET guy, here’s another example of Ruby’s expressive syntax in action. I decided to add bite size snippets of some of the cool things I encountered in Ruby and Rails. If you are interested in more, see my other Ruby posts.

Optional parentheses on method calls are such simple things, but they render some pretty code. Ruby allows you to omit parentheses on method calls in a lot of cases. Take the following code:

puts "Hello World"
puts("Hello World")

The two lines are equivalent, yet the first is just cleaner, don’t you think? Being a diehard C# guy, I do like parentheses, curly braces, and semi-colons, but I’ve got to say Ruby does yield some beautiful code.

In a recent Rails app I used Ryan Bates’ CanCan gem for authorization. It’s a really nice gem and allows you to define abilities for a user elegantly. Using CanCan, you can see how nice and clean the code looks. For example:

class Ability
  include CanCan::Ability

  def initialize(user)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

The code flows nicely; what can an admin do? “can manage all.”

If we were required to add parentheses it’s just is a bunch of extra, unneeded noise, and it breaks up the flow:

class Ability
  include CanCan::Ability

  def initialize(user)
    if user.admin?()
      can(:manage, :all)
    else
      can(:read, :all)
    end
  end
end

user.admin?()<gag> right?() :)

Posted in ruby, ruby on rails and tagged with Rails, Ruby

Damien White

I am a software architect with over 16 years of experience. I simply love coding! I have a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. I'm happy to share what I know in my quest to learn as much as possible. I focus most of my time on web development using Ruby on Rails, Ember.js, and ASP.NET MVC.

comments powered by Disqus