Self-Improvement

기초 3 (블록, 변수 대입, 예외처리(rescue), catch/throw) 본문

프로그래밍/Ruby

기초 3 (블록, 변수 대입, 예외처리(rescue), catch/throw)

JoGeun 2020. 8. 18. 14:51

블록

블록은 중괄호나 do와 end키워드로 둘러싸인 코드이다.

 

each를 이용한 블록 예제

1
2
3
4
5
sum=0
[1,2,3,4].each do |value|
    sum+=value
    puts sum
end
cs

 

 

yield를 이용한 블록 예제

메소드에서 yield문을 사용해서 마치 코드 블록을 하나의 메소드인 것처럼 호출할 수 있다.

1
2
3
4
5
6
7
8
def my_method
    yield
    yield
end
 
my_method do
    puts "hi"
end
cs

 

 

블록을 이용한 파일 내용 읽기 예제

1
2
3
4
5
f=File.open("testfile")
f.each do |line|
    puts "Line : #{line}"
end
f.close
cs

 

 

with_index(읽은 라인 수 출력을 위한)를 이용한 파일 내용 읽기

1
2
3
4
5
f=File.open("testfile")
f.each.with_index do |line,index|
    puts "index : #{index}, Line : #{line}"
end
f.close
cs

 

 

변수 대입 유형 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Case1
a=b=1+2+3         # a=6, b=6
 
# Case2
a=(b=1+2)+3     # a=6, b=3
 
# Case3
a,b=1,2         # a=1, b=2
a,b=b,a         # a=2, b=1
 
# Case4
a,b=1,2,3,4     # a=1, b=2
c,=1,2,3,4         # c=1
 
# Case5
a, *b=1,2,3     # a=1, b=[2, 3]
a,*b=1         # a=1, b=[]
*a, b=1,2,3,4     # a=[1,2,3], b=1
c,*d,e=1,2,3,4    # c=1, d=[2,3], e=4
f,*g,h,i,j=1,2,3,4 # f=1, g=[], h=2, i=3, j=4
cs

 

rescue 예외 처리 형식

else, ensure은 선택해서 작성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
require 'open-uri'
 
f=File.open("test.txt")
begin
    # ..프로세스
rescue
    # .. 에러처리
else
    puts "Congratulations-- no errors!"
ensure
    # 에러와 무관하게 반드시 실행하는 프로세스
end
cs

 

예외처리 실제 구문

1
2
3
4
5
6
7
8
9
require 'open-uri'
 
begin
    eval string
rescue SyntaxError, NameError => boom
    print "String doesn't compile: " + boom
rescue StandardError => bang
    print "Error running script: " + bang
end
cs

 

catch와 throw

rescue는 무언가 잘못되었을 때 실행을 멈추는 데는 효과적이지만 일반적인 실행 중에도 여러 겹으로 둘러싸인 코드 밖으로 탈출할 수 있게 해주는 문법이 catch와 throw이다. 여러개의 루프문에서의 탈출과 같은 느낌

worldlist 파일의 내용을 한줄씩 잃어와서 배열에 넣은 후 배열을 거꾸로 출력하는 코드이다.

이때 throw 구문에서 읽어온 라인이 없을 경우 반복문 while문을 종료하게 된다.

1
2
3
4
5
6
7
8
9
10
word_list = File.open("worldlist")
catch (:done) do
    result = []
    while line=word_list.gets
        word=line.chomp
        throw :done unless word =/^\w+$/
        result << word
    end
    puts result.reverse
end
cs

 

입력을 받는 과정에서 "!"가 존재하면 바로 종료

1
2
3
4
5
6
7
8
9
10
11
def prompt_and_get(prompt)
    print prompt
    res=readline.chomp
    throw :quit_requested if res == "!"
    res
end
 
catch :quit_requested do
    name=prompt_and_get("Name: ")
    age=prompt_and_get("Age: ")
end
cs