2014-04-16 4 views
2

Ruby/Rails working with gsub and arrays과 유사합니다.한 배열의 문자열을 다른 루비의 문자열로 바꾸기

  • 두 개의 배열 "errors"및 "human_readable"이 있습니다.

  • 나는라는 이름의 파일을 읽어 싶습니다
  • 는 "logins.log" 오류를 교체 [X]와 human_readable [X]

  • I 출력이가는 곳, 표준 출력은 괜찮 상관하지 않습니다. 손실

     
    errors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"] 
    human_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"] 
    file = ["logins.log"] 
    
    file= File.read() 
    errors.each 
    

    ... 미안 해요

, 나는이 바보 같은 질문을 알고 난 노력하고 있지만 반복에 엉키지하고있다. 나를 위해 일한 무엇

(나는 다른 대답은 유효 확신하지만이 나를 이해하기 쉬웠다)


#Create the arrays 
errors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"] 
human_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"]

#Create hash from arrays zipped_hash = Hash[errors.zip(human_readable)]

#Open file and relace the errors with their counterparts new_file_content = File.read("login.log").gsub(Regexp.new(errors.join("|")), zipped_hash)

#Dump output to stdout puts new_file_content

이 굉장하고, 덕분에 물건을 많이의 템플릿이 될 것이다 백만.

답변

3
errors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"] 
human_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"] 

zipped_hash = Hash[errors.zip(human_readable)] 
#=> {"0xC0000064"=>"Unknown User", "0xC000006A"=>"Bad Password", "0xC0000071"=>"Expired Password", "0xC0000072"=>"Account Disabled", "0xC0000234"=>"Account Locked"} 

new_file_content = File.read("logins.log").gsub(/\w/) do |word| 
    errors.include?(word) ? zipped_hash[word] : word 
end 

or 

new_file_content = File.read("logins.log").gsub(Regexp.new(errors.join("|")), zipped_hash) 

puts new_file_content 
+1

+1 두 번째 솔루션의 경우 깔끔한 – Nimir

+0

두 번째 솔루션은 상당히 똑똑하고 좋은 추측입니다. – MrYoshiji

+0

감사합니다. 후자를 위해 위의 해를 두는 것 (내가 뭔가를 놓치지 않는다고 가정 할 때). – TheFiddlerWins

관련 문제