嘿我有点问题,我有一个字符串数组text_word,我想用我的文件transform.txt替换一些字母,我的文件看起来像这样:
/t/ 3
/$/ 1
/a/ !
但是当我使用gsub时,我得到一个Enumerator,有人知道如何解决这个问题吗?
text_transform= Array.new
new_words= Array.new
File.open("transform.txt", "r") do |fi|
fi.each_line do |words|
text_transform << words.chomp
end
end
text_transform.each do |transform|
text_word.each do |words|
new_words << words.gsub(transform)
end
end
当你提供一个参数(模式)时,gsub
返回一个Enumerator
。如果要替换,只需添加替换字符串:
pry(main)> 'this is my string'.gsub(/i/, '1')
"th1s 1s my str1ng"
您需要重构代码:
text_transform = Array.new
new_words = Array.new
File.open("transform.txt", "r") do |fi|
fi.each_line do |words|
text_transform << words.chomp.strip.split # "/t/ 3" -> ["/t/", "3"]
end
end
text_transform.each do |pattern, replacement| # pattern = "/t/", replacement = "3"
text_word.each do |words|
new_words << words.gsub(pattern, replacement)
end
end
你可以看到String#gsub
如果第二个参数是
Hash
,并且匹配的文本是其键之一,则相应的值是替换字符串。
你也可以使用IO::readlines
File.readlines('transform.txt', chomp: true).map { |word| word.gsub(/[t$a]/, 't' => 3, '$' => 1, 'a' => '!') }