How does control flow work in Ruby? Provide examples of conditional statements and loops.
In Ruby, control flow refers to the order in which statements are executed based on certain conditions or loops. It allows the program to make decisions, repeat actions, and perform different sets of instructions based on specific criteria. Conditional Statements: Ruby provides several conditional statements that control the flow of execution based on the truth or falsity of certain conditions. 1. if Statement: The `if` statement allows the program to execute a block of code only if a certain condition is true. It has the following syntax: ``` ruby`if condition # code to execute if condition is true end` ``` Example: ``` ruby`x = 5 if x > 3 puts "x is greater than 3" end` ``` 2. if-else Statement: The `if-else` statement extends the `if` statement by providing an alternative block of code to execute when the condition is false. It has the following syntax: ``` ruby`if condition # code to execute if conditio....
Community Answers
Sign in to open profiles and full community answers.
No community answers yet. Be the first to submit one.