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
Primjer:
a = gets.chomp.to_i if a >= 18 puts 'You are eligible to vote.' end
Izlaz:
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
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 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
Primjer:
a = gets.chomp.to_i if a <50 puts 'student is fail' elsif a>= 50 && a <= 60 puts 'student gets d grade' elsif a>= 70 && a <= 80 puts 'student gets b grade' elsif a>= 80 && a <= 90 puts 'student gets a grade' elsif>= 90 && 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 > 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 > 3 ? true : false); puts a
Izlaz:
=>=>=>=>50>