티스토리 뷰

Ruby & Rails

Ruby 처음 배우기 : 조건문

조묵헌 2018. 5. 10. 17:39

조건문 (Conditionals)

if

루비에서 조건문은 if...elsif...else 를 사용합니다.

if user_num < 0
  puts "You picked a negative integer!"
elsif user_num > 0
  puts "You picked a positive integer!"
else
  puts "You picked zero!"
end

# if 표현식
expression if boolean

# 예시
puts "Go next" if true
# same as
if true
  puts "Go next"
end

unless

Unless - 조건식이 false이면 처리가 실행됩니다.

busy = false

unless busy
  puts "I'm OK"
else
  puts "Oh dear! Oh dear! I shall be too late!"
end
# "I'm OK"


# unless 표현식
unless false
  puts "Hello"
end

# 아래와 같이 간단하게 표현할 수 있습니다.
puts "Hello" unless false

Ternary

삼항 연산자는 if...else...end 구문을 쉽게 할용할 수 있게 해 주며, 조건 ? 참일경우 : 거짓일 경우 의 형식으로 사용할 수 있습니다.

dice1 = 5
dice2 = 6
puts dice1 > dice2 ? "dice1 won" : "dice2 won"

# same as
if dice1 > dice2
  puts "dice1 won"
else
  puts "dice2 won"
end

Case

case...when 문은 다른 언어의 switch문과 유사하며, 간단한 문법을 제공합니다.

day = "Monday"

case day
when "Monday"
  puts "Work!"
when "Tuesday"
  puts "Work!"
when "Wednesday"
  puts "Work!"
when "Thursday"
  puts "Work!"
when "Friday"
  puts "Work!"
else
  puts "Rest"
end


# 축약
case day
when "Monday" then puts "Work!"
when "Tuesday" then puts "Work!"
when "Wednesday" then puts "Work!"
when "Thursday" then puts "Work!"
when "Friday" then puts "Work!"
else puts "Rest"
end

'Ruby & Rails' 카테고리의 다른 글

Ruby 처음 배우기 : 메서드  (0) 2018.05.10
Ruby 처음 배우기 : 반복문  (1) 2018.05.10
Ruby 처음 배우기 : Hash, Symbol  (0) 2018.05.10
Ruby 처음 배우기 : 배열  (0) 2018.05.10
Ruby 처음 배우기 : 연산자  (0) 2018.05.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함