gpt4 book ai didi

ruby-on-rails - 在 ruby​​ 中用另一个数组中的字符串替换一个数组中的字符串

转载 作者:数据小太阳 更新时间:2023-10-29 08:47:33 25 4
gpt4 key购买 nike

类似于Ruby/Rails working with gsub and arrays .

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

  • 我想通读一个名为“logins.log”的文件替换error[x] 与 human_readable[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"]<p></p>

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

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

#Dump output to stdout
puts new_file_content

这太棒了,将成为很多东西的模板,非常感谢。

最佳答案

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

关于ruby-on-rails - 在 ruby​​ 中用另一个数组中的字符串替换一个数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com