Ruby 예외 처리와 정규 표현식
Source: Dev.to
예외 처리
Ruby에서 예외를 발생시키고 처리하는 기본적인 방법을 살펴봅니다.
def raise_exception
puts 'I am before the raise.'
raise 'An error has occured'
puts 'I am after the raise' # 실행되지 않음
end
raise_exception
위 예제는 raise 로 예외를 발생시킨 뒤, 예외가 발생한 지점 이후의 코드는 실행되지 않음을 보여줍니다.
def raise_and_rescue
begin
puts 'I am before the raise.'
raise 'An error has occured.'
puts 'I am after the raise.'
rescue
puts 'I am rescued.'
end
puts 'I am after the begin block.'
end
raise_and_rescue
begin … rescue … end 구문을 사용하면 예외가 발생했을 때 rescue 블록이 실행되고, 그 뒤의 코드는 정상적으로 진행됩니다.
다양한 예외 타입을 구분해서 처리할 수도 있습니다.
begin
# ...
rescue OneTypeOfException
# ...
rescue AnotherTypeOfException
# ...
else
# 다른 예외들
end
예외 객체를 잡아 상세 정보를 출력하는 방법:
begin
raise 'A test exception.'
rescue Exception => e
puts e.message # 예외 메시지
puts e.backtrace.inspect # 백트레이스
end
정규 표현식
Ruby에서 정규 표현식을 사용해 문자열을 매칭하고 캡처하는 방법을 살펴봅니다.
m1 = /Ruby/.match("The future is Ruby")
puts m1.class # => MatchData
=~ 연산자를 이용하면 매칭 시작 위치를 반환합니다.
m2 = "The future is Ruby" =~ /Ruby/
puts m2 # => 14 (매칭 시작 위치)
전화번호와 같은 패턴을 캡처하는 예시:
string = "My phone number is (123) 555-1234."
phone_re = /\((\d{3})\)\s+(\d{3})-(\d{4})/
m = phone_re.match(string)
unless m
puts "There was no match..."
exit
end
print "The whole string we started with: "
puts m.string
print "The entire part of the string that matched: "
puts m[0]
puts "The three captures: "
3.times do |index|
puts "Capture ##{index + 1}: #{m.captures[index]}"
end
puts "Here's another way to get at the first capture:"
print "Capture #1: "
puts m[1]
위 코드는 전체 매칭 문자열(m[0])과 각 캡처 그룹(m[1], m[2], m[3])을 출력합니다.