![]() ![]() Now it’s time to see more advanced use cases of the case expression. Which is quite logical : think about the if/elsif indentation. There is no official standard about this, however developers tend to put the when keyword on the same column as case (source : stackoverflow) : case bar Indentation of the case/when statement in Ruby If you have any background with another programming language then you may have also noticed that with Ruby you don't need to end every individual case with a break clause. ![]() The key differences to note are that you no longer need to write the comparison operator or the then keyword. This test is done using comparison = target. It is optional and will execute when nothing matches.Ĭase operates by comparing the target (the expression after the keyword case) with each of the comparison expressions after the when keywords. There can be multiple when statements into a single case statement.Įlse : It is similar to the default keyword in other programming languages. When : It is similar to the case keyword in other programming languages. It takes the variables that will be used by when keyword. There are 3 important keywords that are used in the case statement:Ĭase : It is similar to the switch keyword in other programming languages. The following if expression if name = " Peter Parker " Let's begin by converting a small-sized if expression into a case/when statement. To quote the popular ProgrammingRuby book, "The Ruby case expression is a powerful beast: a multiway if on steroids." So how do you switch to case/when ?Ĭase statements in Ruby are very powerful. Whenever if statements become too long and start looking messy you might want to consider using the case statement to write cleaner code. In Ruby, the classic 'switch statement' is possible with the *case/when* keywords. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |