logo

Ruby If-else izjava

Ruby if else izjava koristi se za testiranje uvjeta. U Rubyju postoje različite vrste naredbi if.

  • izjava if
  • izjava if-else
  • if-else-if (elsif) izjava
  • ternay (skraćeni if ​​iskaz) iskaz

Ruby if izjava

Ruby if naredba testira uvjet. Blok naredba if se izvršava ako je uvjet istinit.

Sintaksa:

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

Primjer:

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

Izlaz:

Ruby if else 2


Ruby ako ne

Ruby if else izjava testira uvjet. Blok naredba if se izvršava ako je uvjet istinit, inače se izvršava blok naredba.

Sintaksa:

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

Primjer:

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

Izlaz:

Ruby if else 4


Ruby if else if (elsif)

Ruby if else if naredba testira uvjet. Blok naredba if se izvršava ako je uvjet istinit, inače se izvršava blok naredba.

Sintaksa:

 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

Primjer:

 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>

Primjer:

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

Izlaz:

Ruby if else 7