LOGO

Ruby If, Else If Command Syntax

April 7, 2014
Ruby If, Else If Command Syntax

Ruby Control Structures: A Concise Overview

The Ruby programming language is characterized by its straightforward and easily understandable control structures. These structures facilitate the creation of logical flows within programs.

The 'If' Statement

Ruby’s if statement allows for conditional execution of code. A block of code will only be executed if a specified condition evaluates to true.

Consider the following example:

if var == 10

print "Variable is 10"

end

'If Else' Statement

The if else statement provides a mechanism for executing one block of code if a condition is true, and a different block if the condition is false.

Here's how it's implemented:

if var == 10

print "Variable is 10"

else

print "Variable is something else"

end

'If Else If' (Elsif) Statement

A notable distinction between Ruby and many other programming languages lies in its handling of "else if" conditions. In Ruby, "else if" is written as elsif, omitting the 'e'.

The following illustrates its usage:

if var == 10

print "Variable is 10"

elsif var == "20"

print "Variable is 20"

else

print "Variable is something else"

end

Ternary Operator

Ruby also supports a ternary operator, offering a concise way to express conditional assignments or expressions. This syntax mirrors that found in many other languages.

For instance:

print "The variable is " + (var == 10 ? "10" : "Not 10")

This code snippet will output "The variable is 10" if the value of 'var' is 10; otherwise, it will output "The variable is Not 10".

#Ruby#if statement#else if#conditional statements#Ruby syntax#programming