Menu
CoddyTech

보장과 정리

Coddy의 C# 개발자를 위한 Ruby 코스 레슨. 48개 중 24번째.

C#의 finally와 Ruby의 ensure는 일반적인 실행 및 예외 처리 과정에서 보호된 구역을 벗어날 때 실행됩니다. C#의 using은 리소스 해제 프로토콜을 추가하지만, ensure만으로 모든 리소스 유형을 자동으로 처리할 수 있는 것은 아닙니다. C#에서는 finally를 벗어날 때 return을 사용할 수 없지만, Ruby에서는 ensure의 return이 앞서 나온 결과를 덮어쓸 수 있습니다. 정리 작업은 결과와 분리해 두세요.

C#: 완전한 프로그램

using System;
using System.Collections.Generic;
using System.Linq;
try{try{throw new ArgumentException("bad");}finally{Console.WriteLine("cleanup");}}
catch(ArgumentException){Console.WriteLine("handled");}

Ruby: 완전한 프로그램

begin
  begin
    raise ArgumentError, "bad"
  ensure
    puts "cleanup"
  end
rescue ArgumentError
  puts "handled"
end
challenge icon

챌린지

쉬움

open을 추가하고, 한 번 yield하며, 블록에서 예외가 발생하더라도 close를 추가하는 with_log(log)를 정의하세요. 성공하면 블록의 결과를 반환하고 오류는 전파하세요. solve는 ok 또는 fail을 읽습니다. done을 반환하거나 ArgumentError를 발생시키는 블록을 사용하세요. done|open,close 또는 error|open,close을 반환하세요.

출력하지 말고 solve(input)에서 텍스트를 반환하세요. 잠긴 드라이버는 반환된 텍스트를 마지막에 개행 문자 하나를 붙여 출력하고, 필수 공개 API를 각각 독립적으로 확인합니다.

코드는 exercise.rb, session.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

require_relative 'exercise'
require_relative 'session'
def check(value)
  raise 'Public API check failed' unless value
end
log = []
check(with_log(log) { 17 } == 17)
check(log == ["open", "close"])
begin
  with_log(log) { raise KeyError, "probe" }
rescue KeyError
  check(log == ["open", "close", "open", "close"])
end
check(log.length == 4)

puts solve(STDIN.read)
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C# 개발자를 위한 Ruby의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러