Written on 12:43:00 PM by S. Potter
Today I wanted to show the implicit and explicit naming conventions in Ruby for newbies. It isn't particularly consistent with another language's conventions, so could cause confusion when reading the Ruby Standard Library (RSL). Where appropriate I also discuss how some of the naming conventions really aid code readability and developer productivity.
ClassName and ModuleName [implicit]Naming classes is very similar to most common conventions following in C++, Java, Python and C#. e.g.
Controlleretc. I am unaware of a class name in the (RSL) that violates this rule. RSL examples of convention usage are Fixnum, Rational, DateTime, Module, NameError, NotImplementedError, NilClass. I realize Fixnum is a little controversial, but I think there is a case for it's naming as above.
variable_name and regular_method_name [implicit]For variable names and methods that do something that isn't dangerous and/or return a non-boolean to the caller, the common underscoring convention is used to name them. This is consistent with Perl and PHP variable naming conventions. RSL examples include: String#strip, Object#instance_eval, Array#sort_by. Please note this is the one convention listed here that is violated in the RSL the most.
method_asking_a_question? [implicit]Suffixing a method that asks a question with a '?' is a great way to tell clients of your code it returns a boolean value to be used in conditional expressions. My favorite RSL example is Object#nil?. This is one of the most important methods, in my mind, that exist in Ruby in conjunction with making Ruby's
niland object of type NilClass. RSL exaples include: Object#is_a?, Hash#has_key?, Object#frozen?. This naming approach is my joint favorite with the following convention that significantly increases readability of code and implicitly improves developer productivity as a side effect.
slightly_dangerous_method! [implicit]For methods that change the internal state of the object in a way that may not be apparent, a '!' is suffixed to the method name to follow this convention. As an example in the RSL, you would probably expect the method
"a string".upcaseto return a copy of the original string in upper case, but the method
"a string".upcase!would probably warn you that it would change the original object's internal state. This is an important distinction to know as a developer writing client code to the String class. This naming convention will keep you out of trouble. If a team mate decides to try out some of your APIs, then you can feel safe knowing you have warned him/her of potential danger spots.