Ruby Basic - 2

woolim park·2021년 3월 14일
0

Ruby Basic

목록 보기
2/9
post-thumbnail

1. 조건문

if expression
	...
elsif expression
	...
else
	...
end

unless 는 elsif 가 없다.

unless expression
	...
else
	...
end

한 줄짜리도 가능

"Hello" if i_am_nice
"Go away" else

2. case 문

case
when expression
	...
when expression
	...
else
	...
end
case test_value
when value
	...
when value
	...
else
	...
end

3. short hand operator

> boolean ? result1 : result2
# y 값이 있으면 y, 없다면 z를 x에 할당.
> x = y || z
# x 값이 없으면 x에 y값을 할당
> x ||= y

4. loop

제어 키워드

  • break: 반복정지
  • next: 다음루프로 점프
  • redo: 해당 루프 반복
  • retry: 전체 루프를 다시
i = 5
loop do
	break if i <= 0
    puts "Countdown: #{i}"
    i -= 1
end
puts "Blast off!"
while boolean
	...
end

until boolean
	...
end

이터레이터를 이용한 반복

5.times do
    puts "Hello !"
end

1.upto(5) { puts "Hello" }
5.downto(1) { puts "Hello" }
(1..5).each { puts "Hello" }
"stirng\nstring\n".each_line {|line| puts line }
"stirng".each_char {|char| puts char }
"stirng".each_byte {|byte| puts byte }
array.each
array.each_index
array.each_with_index
hash.each
hash.each_key
hash.each_value
hash.each_pair

for fruit in ["banana", "apple", "pear"]
	puts fruit.capitalize
end
profile
Javascript Developer

0개의 댓글