Transformation Thursday - C# to Ruby, What is the equivalent of a Namespace in Ruby

July 10, 2014

I am learning Ruby, and when I look at a C# class file, I always see using statements, a namespace declaration, a class declaration and methods. So what is the equivalent of a namespace in Ruby? In other words how to I group a whole bunch of classes into a namespace that I can ship and then will prevent clashes?

Enter the module keyword. A module is a collection of methods and constants. It can group together a bunch of classes and is effectively the equivalent of a namespace in C#.

First here is some C# code that we will work with:

namespace Calculator
{
	public class FancyCalculator
	{
		public FancyCalculator()
		{
		}

		public int Add(int lhs, int rhs)
		{
			return lhs + rhs
		}		
	}
}

Here is how you structure the code using a module.

module Calculator # a namespace
	class FancyCalculator # a class
		def initialize # a constructor
		end

		def add(lhs, rhs) # a method in the class
			lhs + rhs
		end
	end
end

I will be discussing the other parts of this structure in the coming weeks but for now you should be set. The code above is comparable with C# code so it should be easy to see what is going on.

That everyone is the namespace equivalent in Ruby. I will also discuss module some more in the coming days, so stay tuned.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus