Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition.
Decision Making Statements in Ruby :
If statement in Ruby is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
if (condition) # statements to be executed end
You are eligible to vote.
In this ‘if’ statement used to excecute block of code when the condition is true and ‘else’ statement is used to execute a block of code when the condition is false.
if(condition) # code if the condition is true else # code if the condition is false end
You are not eligible to vote.
Here, a user can decide among multiple options. ‘if’ statements are executed from the top down. As soon as one of the conditions controlling the ‘if’ is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if(condition1) # code to be executed if condition1is true elsif(condition2) # code to be executed if condition2 is true else(condition3) # code to be executed if condition3 is true end
Student gets B grade
In Ruby ternary statement is also termed as the shortened if statement. It will first evaluate the expression for true or false value and then execute one of the statements. If the expression is true, then the true statement is executed else false statement will get executed.
test-expression ? if-true-expression : if-false-expression
- Ruby | Set replace() function
- Ruby | Set reset() function
- Ruby | Exception Handling in Threads | Set - 1
- Ruby | Set >= method
- Ruby | Set merge() function
- Ruby | Set member?() function
- Object-Oriented Programming in Ruby | Set 1
- Ruby | Set include?() function
- Ruby | Set delete? function
- Ruby | Set delete() function
- Ruby | Set compare_by_identity? function
- Ruby | Set compare_by_identity() function
- Ruby | Set add? function
- Ruby | Set clear() function
- Ruby | Set << method
- Ruby | Set < method
- Ruby | Set + method
- Ruby | Set add() method
- Ruby | Set & method
- Ruby | Set - method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.