简体   繁体   中英

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:

/t/ 3

/$/ 1

/a/ !

But when I use gsub I get an Enumerator back, does anyone know how to fix this?

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

If the second argument is a Hash , and the matched text is one of its keys, the corresponding value is the replacement string.

Also you can use 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). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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