2

Similar to Ruby/Rails working with gsub and arrays.

  • I have two arrays, "errors" and "human_readable".

  • I would like to read through a file named "logins.log" replace error[x] with human_readable[x]

  • I don't care where the output goes, stdout is fine.

    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 
    

    lost...

I am sorry, I know this is a dumb question and I am trying but I am getting tangled up in the iteration.

What worked for me (I am sure the other answer is valid but this was easier for me to understand)


 #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

This is awesome and will become the template for a lot of stuff, thanks a million.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Putting the solution above for posterity (assuming I got am not missing something).
+1 - you may want to use Regexp#union instead of String#join as it will escape special characters for you - Regexp.union(%w(^ foo.bar)) #=> /\^|foo\.bar/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.