logo

루비 If-else 문

Ruby if else 문은 조건을 테스트하는 데 사용됩니다. Ruby에는 다양한 유형의 if 문이 있습니다.

  • if 문
  • if-else 문
  • if-else-if(elsif) 문
  • ternay(단축된 if 문) 문

루비 if 문

Ruby if 문은 조건을 테스트합니다. 조건이 참이면 if 블록 문이 실행됩니다.

통사론:

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

예:

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

산출:

루비 if else 2


루비라면

Ruby if else 문은 조건을 테스트합니다. 조건이 참이면 if 블록 문이 실행되고, 그렇지 않으면 else 블록 문이 실행됩니다.

통사론:

 if(condition) //code if condition is true else //code if condition is false end 
루비 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 

산출:

루비 if else 4


루비 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 
루비 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 

산출:

루비 if else 7