2017-02-28 2 views
-1

파일 읽기 프로그램이 있습니다. 이 프로그램은 .txt 파일을 읽고 그것에 일부 기능을 실행합니다. 파일 이름별로 기능을 변경하고 싶습니다. .txt 파일의 이름 지정 규칙은 A001.txt, B001, C001 ... 등입니다. if-else 문을 사용하여 함수를 변경하고 있습니다.파일 읽기 및 파일 이름 변경 기능

def Function1(input) 
    if filename =~ /A.+\.txt/ 
    some process.... 
    elsif filename =~ /B.+\.txt/ 
    some process.... 
    ..... 
end 

def Funcition2(input) 
    if filename =~ /A.+\.txt/ 
    some process.... 
    elsif filename =~ /B.+\.txt/ 
    some process.... 
     ..... 
end 

필자는 비슷한 기능을 가지고 있습니다. 이 코드는 효율적이고 읽기 쉽지 않습니다. 파일을 읽을 때 기능을 변경하는 가장 좋은 방법은 무엇입니까?

+0

경고. 첫 번째 정규식은 아마도 당신이 원하는 바가 아닌'BA001.txt' 파일 이름과 일치합니다. 또한'A001.txt2'와 일치합니다. 정규식의 시작과 끝을'/^A. + \. txt $ /'처럼 고정하고 싶습니다. 또한 대소 문자를 구분하지 않도록하는 것이 좋습니다. –

답변

0

스위치 statment - case -를 사용할 수 있습니다. 여기에 이전의 대답입니다 :이 같은 How to write a Ruby switch statement (case...when) with regex and backreferences?

기본적으로 뭔가 :

def Function1(input) 
    prefix = filename[0].downcase 
    handler = "import_#{preview}_file" 
    handler = 'import_unknown_file' if !respond_to?(handler) 
    send(handler, input) 
end 

def import_a_file(input); end 
def import_b_file(input); end 
def import_unknown_file(input); end 

당신은에 한 단계 더이 걸릴 수 있습니다 :

filenames.each do |filename| 
    case filename 
    when /A.+\.txt/ 
    function 1 
    when /B.+\.txt/ 
    function 2 
    else 
    function 3 
    end 
end 
0

나는 동적 인 방법을 사용하는 등 이런 종류의 일을 요구 더 읽기 쉽게하기 :

HANDLERS_FOR_PREFIXES = { 
    'a'  => :import_account_file, 
    'b'  => :import_balance_file, 
    'default' => :import_other_file 
} 

def Function1(input) 
    prefix = filename[0].downcase 
    handler = HANDLERS_FOR_PREFIXES[prefix] || HANDLERS_FOR_PREFIXES['default'] 
    send(handler, input) 
end 

def import_account_file(input); end 

그러나 나는 당신이 파일을 처리하는 것이 중요합니다 (은행 정보를 가져 오는 경우 거래를 가져 오기 전에 계정을 가져와야합니다). 따라서 다음과 같은 것을하는 것이 합리적 일 수 있습니다.

FILE_HANDLERS = { 
    'A*.txt' => :import_account_file, 
    'T*.txt' => :import_transaction_file 
} 

def Function1(input) 
    FILE_HANDLERS.each do |file_pattern, handler| 
    Dir.glob(file_pattern).each do |filename| 
     File.open(filename) do |f| 
     f.each_line do |line| 
      parsed_line = parse(parse) 
      send(handler, parsed_line); 
     end 
     end 
    end 
    end 
end 

깊은 중첩을 없애기 위해 리팩토링을했지만.

마지막으로 코드가 복잡해지면 각 파일 유형을 처리하기 위해 별도의 클래스로 분리해야 할 수 있습니다. 이렇게하면 코드를 재사용하고 분리 할 수있는 많은 기회가 제공됩니다. 예 :

class AccountImporter < Importer 
    def initialize(input); end 
    def process 
end 

HANDLERS_FOR_PREFIXES = { 
    'a'  => AccountImporter, 
    ... 
} 

def Function1(input) 
    prefix = filename[0].downcase 
    handler = HANDLERS_FOR_PREFIXES[prefix] || HANDLERS_FOR_PREFIXES['default'] 
    handler.new(input).process 
end