logo

Declarație Ruby If-else

Declarația Ruby if else este folosită pentru a testa condiția. Există diferite tipuri de declarații if în Ruby.

  • declarația dacă
  • declarație dacă-altfel
  • if-else-if (elsif) declarație
  • ternay (scurtat if statement) declarație

Ruby if declarație

Ruby if testează condiția. Instrucțiunea if block este executată dacă condiția este adevărată.

Sintaxă:

 if (condition) //code to be executed end 
Ruby dacă altceva 1

Exemplu:

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

Ieșire:

Ruby dacă altceva 2


Ruby dacă altceva

Declarația Ruby if else testează condiția. Instrucțiunea if block este executată dacă condiția este adevărată, altfel instrucțiunea block este executată.

Sintaxă:

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

Exemplu:

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

Ieșire:

Ruby dacă altceva 4


Ruby if else if (elsif)

Ruby if else if testează condiția. Instrucțiunea if block este executată dacă condiția este adevărată, altfel instrucțiunea block este executată.

Sintaxă:

 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 dacă altceva 5

Exemplu:

 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>

Exemplu:

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

Ieșire:

Ruby dacă altceva 7