How?

moduleCalculator# a namespace
classFancyCalculator# a class
definitialize# a constructor
enddefadd(lhs,rhs)# a method in the class
lhs+rhsendendend

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

C#:

varcalculator=newCalculator();

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.

moduleCalculator# a namespace
classFancyCalculator# a class
definitialize(name)@name=nameenddefadd(lhs,rhs)# a method in the class
lhs+rhsendendend

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.