logo

Інструкція Ruby If-else

Оператор Ruby if else використовується для перевірки умови. У Ruby існують різні типи операторів if.

  • оператор if
  • оператор if-else
  • оператор if-else-if (elsif).
  • ternay (скорочений оператор if).

Оператор Ruby if

Оператор Ruby if перевіряє умову. Інструкція блоку if виконується, якщо умова виконується.

Синтаксис:

 if (condition) //code to be executed end 
Ruby if else 1

приклад:

 a = gets.chomp.to_i if a >= 18 puts 'You are eligible to vote.' end 

Вихід:

Ruby if else 2


Рубі, якщо інакше

Оператор Ruby if else перевіряє умову. Оператор блоку if виконується, якщо умова виконується, інакше виконується оператор блоку else.

Синтаксис:

 if(condition) //code if condition is true else //code if condition is false end 
Ruby if else 3

приклад:

 a = gets.chomp.to_i if a >= 18 puts 'You are eligible to vote.' else puts 'You are not eligible to vote.' end 

Вихід:

Ruby if else 4


Ruby if else if (elsif)

Інструкція Ruby if else if перевіряє умову. Оператор блоку if виконується, якщо умова виконується, інакше виконується оператор блоку else.

Синтаксис:

 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 
Ruby if else 5

приклад:

 a = gets.chomp.to_i if a <50 puts 'student is fail' elsif a>= 50 &amp;&amp; a <= 60 puts 'student gets d grade' elsif a>= 70 &amp;&amp; a <= 80 puts 'student gets b grade' elsif a>= 80 &amp;&amp; a <= 90 puts 'student gets a grade' elsif>= 90 &amp;&amp; a <= 100 puts 'student gets a+ grade' end < pre> <p>Output:</p> <img src="//techcodeview.com/img/ruby-tutorial/72/ruby-if-else-statement-6.webp" alt="Ruby if else 6"> <br> <br> <hr> <h2>Ruby ternary Statement</h2> <p>In Ruby ternary statement, the if statement is shortened. First it evaluats an expression for true or false value then execute one of the statements.</p> <p> <strong>Syntax:</strong> </p> <pre> test-expression ? if-true-expression : if-false-expression </pre> <p> <strong>Example:</strong> </p> <pre> var = gets.chomp.to_i; a = (var &gt; 3 ? true : false); puts a </pre> <p>Output:</p> <img src="//techcodeview.com/img/ruby-tutorial/72/ruby-if-else-statement-7.webp" alt="Ruby if else 7"> <br> <br> <hr></=></=></=></=></50>

приклад:

 var = gets.chomp.to_i; a = (var &gt; 3 ? true : false); puts a 

Вихід:

Ruby if else 7