Replace strings from one array with strings in another in ruby

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.

ruby-on-rails
ruby
arrays
replace
asked on Stack Overflow Apr 16, 2014 by TheFiddlerWins • edited May 23, 2017 by Community

1 Answer

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
answered on Stack Overflow Apr 16, 2014 by bjhaid

User contributions licensed under CC BY-SA 3.0