[英]Replace strings from one array with strings in another in ruby
Similar to Ruby/Rails working with gsub and arrays . 类似于Ruby / Rails使用gsub和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] 我想通读一个名为“ logins.log”的文件,将error [x]替换为human_ready [x]
I don't care where the output goes, stdout is fine. 我不在乎输出到哪里,stdout很好。
\nerrors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"]错误= [“ 0xC0000064”,“ 0xC000006A”,“ 0xC0000071”,“ 0xC0000072”,“ 0xC0000234”]\nhuman_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"]
human_可读= [“未知用户”,“密码错误”,“密码过期”,“帐户已禁用”,“帐户已锁定”] \nfile = ["logins.log"]
文件= [“ logins.log”]\n\nfile= File.read()
file = File.read()\nerrors.each
errors.each \n
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. 太棒了,感谢您一百万,它将成为很多东西的模板。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.