생활코딩

Coding Everybody

코스 전체목록

닫기

루비의 코드블록

본 수업은 루비에 대한 내용만을 다루고 있습니다.

블록(block)이란 무엇인가?

Ruby

5.times() {|i| puts i}
2.times() {puts '2times'}
3.upto(5) {|item| puts item}

실행결과

0
1
2
3
4
2times
2times
3
4
5

ideone.com

 

블록을 이용한 반복

 

Ruby

5.times(){|i| puts i}

i = 0
while i < 5
  puts i
  i = i + 1
end

실행결과

0
1
2
3
4
0
1
2
3
4

ideone.com

 

배열과 블록

Ruby 1

arr = ['A', 'B', 'C']
arr.each(){|i| puts i}

for value in arr
  puts value
end

실행결과

A
B
C
A
B
C

ideone.com

Ruby 2

arr = [1, 3, 56, 7, 13 , 52]
arr.delete_if() do |item|
  item > 7
end
puts arr

실행결과

1
3
7

ideone.com

댓글

댓글 본문
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기