.NET to Ruby: Namespacing, Naming Conventions, Comments & Documentation

Gavin Miller
Share

Ruby is an opinionated language, and it has an opinionated community. This is a great thing. It keeps the language clean, understandable, and fun.

Ruby can be antagonistic when it comes to a framework like .NET, and I’ll touch on that in this post. Additionally, we’re going to quickly cover namespacing, touch on naming conventions, and then drop into Comments & Documentation.

Namespacing

Programs that we write use namespaces to serve two purposes: 1. To group code into related functional groups and 2. To prevent methods, classes, variables, and constants from colliding with one another. In .NET we use the namespace keyword to namespace our code, in a nice and self evident manner. The namespace syntax is wrapped around the code you want to include within the namespace, and it is contained within the opening and closing curly braces { }:

namespace FooBar {
    // ...
}

In Ruby the keyword module is used to namespace your code:

module Fizz
  # ...
end

You’ll remember from the post on Ruby Classes that module’s aren’t used just for namespacing, they’re also used for creating mixins – checkout the post for a more detailed look at mixins.

Naming Conventions

Ruby’s naming conventions are fairly easy to understand. We’ve covered most of these naming conventions in previous posts, but they’re worth mentioning in a single location:

Type          .NET           Ruby
Namespaces    CamelCase      CamelCase
Classes       CamelCase      CamelCase
Methods       CamelCase      underscores_and_lowercase
Variables     camelBack      underscores_and_lowercase
Constants     CamelCase      ALL_CAPS

You may know CamelCase by it’s alternative name PascalCase.

The one thing we haven’t touched on in previous posts is writing constants in Ruby. Ruby constants are written in ALL_CAPS, and they can actually be re-assigned as well, but Ruby is going to issue a warning if it happens:

IMPORTANT_VALUE = 1
puts "Important Value: #{IMPORTANT_VALUE}"

IMPORTANT_VALUE = 2
# A warning is issued after the above line executes: 
#    warning: already initialized constant
puts "Important Value: #{IMPORTANT_VALUE}"

Add the above with Ruby’s @instance_variable notation, and @@class_variable notation which we covered in the post on Ruby Methods, and Variables, and you’ve got the majority of Ruby’s naming conventions.

Comments & Documentation

Now for the past few posts I’ve been using comments but have never explained that I was actually using a comment. So let’s cover that aspect. For single line comments in Ruby you can use the hash character.

# This is a comment

If we had wanted to create a multi-line comment, we could have used the following:

=begin
  Comment goes here. =begin and =end must start
  at the left margin otherwise they are ignored.
=end

Multi-line commenting should be used infrequently in code. Instead, mutli-line comments are better suited from commenting out large sections of code while you’re developing. For large blocks of comments (such as in documentation) using the hash is preferred.

When it comes to documentation the thing I like about Ruby is that the documentation tools come bundled with the core language via a tool called RDoc. No more searching to figure out whether you should use NDoc, Sandcastle, GhostDoc, Doxygen, or the latest flavor of the month, and whether or not the project will live as long as your project will – RDoc is there today, and it will be there tomorrow. The other nice feature is that RDoc supports Markup, so it’s nice and easy to write your documentation and read it from within the source code, as well as process it into documentation for the web. If you’re hungry for more details, the RDoc README is a great place to go.

Next of all, the Ruby core documentation can be found online at http://ruby-doc.org/core. No more searching MSDN! Ruby’s documentation is very helpful, and in most cases contains concise examples of how to use a particular method. For example let’s compare the C# documentation for String.Trim() with the mostly equivalent method String#strip. I say mostly equivalent because the .NET documentation is not clear on whether it removes newline characters like rn or not… Back to the comparison, here’s the documentation for trim:

using System;

public class Example
{
   public static void Main()
   {
      Console.Write("Enter your first name: ");
      string firstName = Console.ReadLine();

      Console.Write("Enter your middle name or initial: ");
      string middleName = Console.ReadLine();

      Console.Write("Enter your last name: ");
      string lastName = Console.ReadLine();

      Console.WriteLine();
      Console.WriteLine("You entered '{0}', '{1}', and '{2}'.",
                        firstName, middleName, lastName);

      string name = (firstName.Trim() + " " + middleName.Trim()).Trim() + " " +
                    lastName.Trim();
      Console.WriteLine("The result is " + name + ".");
   }
}
// The following is possible output from this example:
//       Enter your first name:    John
//       Enter your middle name or initial:
//       Enter your last name:    Doe
//
//       You entered '   John  ', '', and '   Doe'.
//       The result is John Doe

What kind of monstrosity is that! I get frustrated with an example like this because it takes so much work to figure out what’s actually happening. Contrast that with the Ruby documentation:

# str.strip -> new_str
# Returns a copy of str with leading and trailing whitespace removed.
"    hello    ".strip   #=> "hello"
"tgoodbyern".strip   #=> "goodbye"

Yup, that’s the entire method documentation for strip. You see one of Ruby’s goals is to make it a fun language to program in, and in the midst of that goal all the cruft has been removed. Only what is necessary is left. Whereas looking at the C# example, you have to read down to the 19th line just to get to the Trim() function. And then you have to parse through the braces, quotes, and concatenations. Blekk!

The other great thing about Ruby is that if you don’t like the documentation for a particular method and think that it could be cleaned up, you can submit a patch for that piece of documentation. You see Ruby enables coders to get things done and to give back if something is lacking. When was the last time MS enabled you to do anything with C#, and .NET other than pay through the teeth for their software licenses!

Alright enough of my ranting. Now I hear you asking what happens if I’m not connected to the internet? How do I get access to all that great documentation? That’s simple – with a tool called ri. ri is Ruby’s built in offline documentation viewer. Let’s say you want to know what methods are available for String, just type in

ri String

And ri will produce for you all the methods that can be run against String. If you want to dig deeper into what a method does, append the method name to its class:

ri String#strip

ri is a great tool for exploring what is available in the language and certainly beats accidentally hitting F1 in Visual Studio! One important thing to note is that if you’re running Ruby 1.8.7 you’ll want to install the rdoc-data gem, and perform the following steps:

$ gem install rdoc rdoc-data
$ rdoc-data --install

This gem fixes the ri documentation, and makes it more useful. This issue is fixed in 1.9.2, so no need to worry about it if you’re on that version.

And that draws us to a close on this post. In this post we covered Namespacing, Naming Conventions, Comments & Documentation within Ruby. We also looked at how to write constants in Ruby.

In the next post we’ll do a deep dive into Ruby’s type system, and look at what’s going on under the Ruby hood.