Transformation Thursday - C# to Ruby, What is the equivalent of a Class in Ruby
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.
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
Now let’s take a look at the Ruby code and discuss that.
Classes in Ruby are first class objects, you will create a new class a little different then you do in C#
var calculator = new Calculator();
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.
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.
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.