简体   繁体   English

如何在Ruby中对文件使用gsub?

[英]How to use gsub with a file in Ruby?

Hey I've a little problem, I've a string array text_word and I want to replace some letters with my file transform.txt, my file looks like this: 嘿,我有一个小问题,我有一个字符串数组text_word,我想用我的文件transform.txt替换一些字母,我的文件看起来像这样:

/t/ 3

/$/ 1

/a/ !

But when I use gsub I get an Enumerator back, does anyone know how to fix this? 但是,当我使用gsub时,我又得到了一个枚举器,有人知道如何解决此问题吗?

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

You can see String#gsub 您可以看到String#gsub

If the second argument is a Hash , and the matched text is one of its keys, the corresponding value is the replacement string. 如果第二个参数是Hash ,并且匹配的文本是其键之一,则对应的值是替换字符串。

Also you can use IO::readlines 您也可以使用IO::readlines

File.readlines('transform.txt', chomp: true).map { |word| word.gsub(/[t$a]/, 't' => 3, '$' => 1, 'a' => '!') }

gsub returns an Enumerator when you provide just one argument (the pattern). 当您仅提供一个参数(模式)时, gsub将返回一个Enumerator If you want to replace just add the replacement string: 如果要替换,只需添加替换字符串:

pry(main)> 'this is my string'.gsub(/i/, '1')
"th1s 1s my str1ng"

You need to refactor your code: 您需要重构代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM