Method Idioms in Ruby

Sunday, July 29, 2007

I really like Ruby’s idiomatic use of ? and ! token characters at the end of method names to indicate the method’s purpose: a predicate or a mutator (or otherwise destructive method), respectively. The benefits can be seen with examples.

If the task is replacing a substring inside of a larger string, JavaScript would have it done like this:

str = str.replace(/foo/g, 'bar');

The issue here, especially when you have a long LHS, is that the str = str... bit becomes redundant. In Ruby you could mirror this code as such:

str = str.gsub(/foo/, 'bar');

But then it gets better. Ruby has another method, gsub! that uses the mutator idiom to accomplish the same task in place. The code becomes:

str.gsub!(/foo/, 'bar');

This just ends up being much cleaner and more direct, in my opinion. I would love to see this idiom spread to other languages, especially ones in which I have a personal interest (JavaScript/ES4, Python). There are several more examples of these idioms throughout Ruby code that I won’t get into here, but hopefully you see the benefit from this small snippet.

See also: String.gsub!, FileTest.exist?, Array.flatten!

tagged: asides, awesome, software
written by Brad Fults

Add your thoughts | Trackback URL

Archived at: http://h3h.net/2007/07/method-idioms-in-ruby/

2 responses

  1. Edward O'Connor

    FYI, Ruby got this idiom from Scheme.

  2. Brad

    Ah, I didn’t know that. I never made it all the way to Scheme…I lost interest somewhere around Common Lisp. :)

  3. Comment Preview

Leave a comment

Comments are posted at the discretion of the site owner. Please try to be respectful, insightful and otherwise useful to society as a whole.

(X)HTML is allowed. You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <cite> <code> <dfn> <em> <kbd> <q cite=""> <samp> <strike> <strong> <sub> <sup> <var>