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.
Ruby
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.
C#
Ruby
C#
Ruby
C#
Ruby
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);} |
1
2
3
| if i == 1 puts iend |
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 1puts i if i == 1# short hand 2if i == 1 then puts i end#short hand 3if 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);} |
1
2
3
4
5
| if (i == 2) puts ielse puts iend |
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 ); |
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);} |
1
2
3
4
5
6
7
| if i == 1 puts ielsif i == 2 puts ielse puts iend |
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.Sign up here with your email
ConversionConversion EmoticonEmoticon