Transformation Thursday - C# to Ruby, What is the equivalent of a Method in Ruby
I am learning Ruby and thought it would be useful to other .NET developers coming to Ruby to understand the differences.
I covered Namespaces and Classes previously and would like to follow that up with the next part Methods.
Here is our FancyCalculator code again.
In C# you need to declare your method as either private, public, protected, internal or protected internal. Depending on the access modifier you choose your method will be visible to only the class it is defined in or other classes. By not declaring an access modifier, you default your method to being private.
To jog our memory as to what the different access modifiers mean I have summarized them here.
Private: Access is limited to the containing type. Public : Access is not restricted. Protected: Access is limited to the containing class or types derived from the containing class. Internal: Access is limited to the current assembly. Protected Internal: Access is limited to the current assembly or types derived from the containing class.
Your method then needs to state whether it returns a value; reference type or void aka nothing aka nada aka niente aka niks. If we are returning anything from our method, we use the return keyword together with the result we want to return.
Here is my Ruby code again.
The magic line is this
In Ruby, all methods are public so everyone that has access to our class has access to its method. If we wanted to declare a method as private, we can do so by placing the private key once above the method we want private so let me illustrate this
From what I gather it’s practice in the Ruby community to indent the methods below the private keyword, this makes it much easier to see which methods are all private.
Another approach to making methods private is to pass the method symbols (we will cover symbols soon) to the private keyword as such:
In Ruby, you don’t need to use the return keyword explicitly in your method. In your method, the last line will always be returned. Also as you can see there is no indication as to what will be returned from the method.
Major differences here are:
- No return type needs to be declared on the method
- The last statement in a method will be returned. You can though at any time return something out of the method
- Both languages have access modifiers but unlike C# Ruby defaults to methods being public and any private methods must be explicitly declared.