C# vs Ruby: If…Then…Else

Everyone needs the powerful “if…then…else” when doing development. With ruby it is actually quite simple and close to C#, but you need to see it so you can understand the differences.
Ruby has the traditional operators: “==”, “||”, “&&”, “<", ">” etc. So you can still use those like normal. They also have some modifications of those which will explained in another post because of the nuances of them.

Traditional If Statement

C#
1
2
3
4
if(i == 2)
{
    Console.WriteLine(i);
}
Ruby
1
2
3
if i == 1
    puts i
end
The ruby code above can works with parenthesis, but a lot of the code I see doesn’t use them. There is a whole discussion that can be had about when and where to use parenthesis which is for another time and date, just wanted you to be aware.
Here are a couple of other ways for your code to be formatted which can allow for better readability or just a quick way to throw an if in where needed.
1
2
3
4
5
6
7
8
# short hand 1
puts i if i == 1
 
# short hand 2
if i == 1 then puts i end
 
#short hand 3
if i == 1 : puts i end

If…Else

For those times that the if doesn’t work and you need to output something else.
C#
1
2
3
4
5
6
if(i == 2){
    Console.WriteLine(i);
}
else {
    Console.WriteLine(i);
}
Ruby
1
2
3
4
5
if (i == 2)
    puts i
else
    puts i
end

If…Else Shorthand

This can be useful, but a bit of a pain to implement at times. I am curios how often others actually use these if then else shorthands?
C#
1
Console.WriteLine(  i == 2 ? i++ : 3 );
Ruby
1
i == 2 ? (puts i) : (puts 1)

If…ElseIf…Else

As you have probably notice a lot of this is fairly similar just note for the Ruby first of else if there is no e in the elseif. That is about the only difference.
C#
1
2
3
4
5
6
7
8
9
if(i == 2){
    Console.WriteLine(i);
}
else if(i == 3){
    Console.WriteLine(i);
}
else{
    Console.WriteLine(i);
}
Ruby
1
2
3
4
5
6
7
if i == 1
    puts i
elsif i == 2
    puts i
else
    puts i
end

Conclusion

If statements are easy to do and quite essential when programming. There are probably many more ways in both languages to do these. I just was showing a few. If you are aware of other ways please post them in the comments.
Previous
Next Post »