Method/Function in Ruby and C#

Something else I like to do when I am looking at a new language is see what what a method/function in Ruby (since that was my first language) and whatever I am learning now, in this case, C#. I am going to make a simple method in ruby that will add two numbers together and return the sum. Then I will do the same in C#

In ruby, this is going to take the two arguments and add them together.

def addition(num1, num2)
  num1 + num2
end

sum = addition(1, 2)
puts sum #should return 3

If I wanted to do the exact same thing in C#, it would look something like this.

using System;

class Example
{
    static int Addition(int num1, int num2)
    {
        return num1 + num2;
    }

    static void Main()
    {
        int sum = Addition(1, 2);
        Console.WriteLine(sum); // should return 3
    }
}

Above gives me the same thing, but in C#. I had to remind myself frequently at first to make sure each integer has a datatype.


Another simple example would be checking if a number is odd

So in Ruby, I would have to do the following

def is_odd(number)
  number.odd?
end

result1 = is_odd(3)
result2 = is_odd(2)

puts result1  #returns true
puts result2  #returns false

Ruby has some handy built in methods like the one used above. If I was wanting to really get into it, I would write out the logic behind method instead of using the built-in one, but for an example I think this is fine.

And in C#, you do actually have to write out the logic. So if the modulo of a number is anything aside from 0, it is odd. You can’t divide an odd number by two and get a modulo of 0.

using System;

class Program
{
    static bool IsOdd(int number)
    {
        return number % 2 != 0;
    }

    static void Main()
    {
        bool result1 = IsOdd(3);
        Console.WriteLine(result1); // return true
        bool result2 = IsOdd(4);
        Console.WriteLine(result2); // return false
    }
}

The nice thing about C# is that everything is written out for you to see.
Whether or not you like that or find it is entirely too much information is up to you

Brendan Bondurant Avatar

About the author

More about Brendan · LinkedIn · GitHub


Comments

Leave a Reply

Discover more from Brendan Bondurant

Subscribe now to keep reading and get access to the full archive.

Continue reading