The following case example detects where a number falls amongst a group of different ranges.
Ruby case switch.
Ruby case statement syntax case expression when expression expression then code.
In other programming languages this is known as a switch statement.
Ruby case statement last updated.
Basically if elsif else notice there s nothing after the word case.
Number ranges and the case statement.
In most computer languages the case or conditional also known as switch statement compares the value of a variable with that of several constants or literals and executes the first path with a matching case in ruby it s a bit more flexible and powerful.
Else code end compares the expression specified by case and that specified by when using the operator and executes the code of the when clause that matches.
The case statement is also particularly useful when used in conjunction with number ranges for details of ranges read the ruby ranges chapter of this book.
The components of a case statement in ruby.
Ruby 入門 条件分岐.
The expression specified by the when clause is evaluated as the left operand.
The case statement is a multiway branch statement just like a switch statement in other languages.
In this post you will learn a few different use cases and how it all really works under the hood.
It provides an easy way to forward execution to different parts of code based on the value of the expression.
Score 70 result case score when 0 40 then fail when 41 60 then pass when 61 70 then pass.
Whenever you need to use some if elsif statements you could consider using a ruby case statement instead.