用ruby中的另一个数组替换另一个数组中的字符串

时间:2014-04-16 14:04:35

标签: ruby-on-rails ruby arrays replace

Ruby/Rails working with gsub and arrays类似。

  • 我有两个数组,“errors”和“human_readable”。

  • 我想通读一个名为“logins.log”的文件替换 带有human_readable [x]

  • 的错误[x]
  • 我不关心输出在哪里,stdout很好。

    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

这很棒,并且会成为很多东西的模板,感谢百万。

1 个答案:

答案 0 :(得分: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
相关问题