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

July 17, 2014

Why?

I am learning Ruby and thought it would be useful to other .NET developers coming to Ruby to understand the different constructs.

I covered Namespaces previously and would like to follow that up with the next logical part Classes.

Let’s look at our previous FancyCalculator code.

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

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

Here we see that our class is the container for our properties and variables. I am not going to spend too much time on this as this is pretty straight-forward C# code

How?

Now let’s take a look at the Ruby code and discuss that.

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

Classes in Ruby are first class objects, you will create a new class a little different then you do in C#

C#:

var calculator = new Calculator();

Ruby:

calc = FancyCalculator.new

If you want your constructor to take parameters unlike C# you won’t be creating a new constructor method with the parameters you need. You will rather use the initialize method for your parameters.

module Calculator # a namespace
	class FancyCalculator # a class
		def initialize(name)
			@name = name
		end

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

We will dive into constructors a bit more next week. For now, you just need to know that you will need to define an initialize method pass the parameters and then set the properties or do any work you need to with the parameters.

Conclusion

There are two differences when it comes to C# and Ruby classes. The one being that you use Class.new instead of new Class() and the other is that you pass your constructor parameters to the initialize method instead of overriding the new method on the class.

Further, then the two differences mentioned class are pretty straight-forward and easy to understand.


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