Let s see an example where we want to print some message depending on what range a value falls in.
Ruby case statement return value.
One equals sign in ruby means assignment make sure to use when you want to find out if two things are the same.
This returned value will be the value of the last statement.
Return values from methods.
Ruby case ranges.
This will produce the following result.
The statement for i in 0 5 will allow i to take values in the range from 0 to 5 including 5.
If you don t this right you won t get the expected results.
Notice that we use two equal symbols to mean equality.
Will insert the default value for keys that are not found.
Here we have explained if expression ternary if unless expression modifier if and unless and case expression.
True and any other object are true values.
All the expressions described here return a value.
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.
So you can safely wrap a case statement in a method call and ruby will have no problems with it.
Hash has value value tests whether hash contains the given value.
With an if statement you can check if something is true.
Hash indexes keys returns a new array consisting of values for the given key s.
This can quickly become cumbersome however when a need arises to evaluate a large number of conditions.
Nil and false are false values.
A case statement will always return a single object just like a method call.
For the tests in these control expressions.
The case statement is more flexible than it might appear at first sight.
But when you want to check for the opposite not true false.
1 value is set 3 value is set ruby case statement syntax case expression when expression expression then code.
Hash index value returns the key for the given value in hash nil if no matching value is found.
A much easier way to handle such situations is to use the ruby case statement the syntax for which is defined as follows.
The return statement in ruby is used to return one or more values.
Result case value when match1 then result1 when match2 then result2 when match3 then result3 when match4 then result4.
Usr bin ruby for i in 0 5 puts value of local variable is i end here we have defined the range 0 5.
Every method in ruby returns a value by default.
Case capacity when 0 you ran out of gas.
For example the above version of the case statement ca be re written like this.