将String替换为Int

时间:2012-12-12 18:58:54

标签: ruby

#! /usr/bin/env ruby

filepath = "chapter1.xhtml"
text = File.read(filepath)


i=1

text = File.read(filepath)

while i!=91


replace = text.gsub(/123123/) do |match|
  match=i.to_s()
end
File.open(filepath, "w") {|file| file.puts replace}
    i=i+1
end

我想将Ruby1,Ruby1,Ruby1替换为Ruby1,Ruby2,Ruby3 但我的代码不起作用。我的错在哪里?我该如何解决?

例如

Ruby1 Ruby1 Ruby1

替换为

Ruby1 Ruby2 Ruby3

2 个答案:

答案 0 :(得分:0)

text = File.read(filepath)读取整个文件,因此您可以在循环中一次又一次地读取它。

File.open的同意,删除文件90次。

My code doesn't work.

你应该解释发生了什么,错误信息等。

答案 1 :(得分:0)

input_path  = "chapter1.xhtml"
output_path = "new.txt"
#input = 'input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">'
string_to_replace = 'bolum1'
File.open(output_path, "w") do |output|
    File.open(input_path, 'r') do |f|
        f.readlines.each do |line|
            counter = 0
#            result = input.gsub(string_to_replace) do |match|
            result = line.gsub(string_to_replace) do |match|
#                puts "found=#{match}"
                counter += 1
                match[-1, 1] = counter.to_s # replace last char by counter
#                puts "replace=#{match}"
                match # the result of the block replaces the matched string
            end
            p result
            output.write(result)
        end
    end # input file will automatically be closed at the end of the block
end # output file will automatically be closed at the end of the block

文件chapter1.xhtml:

input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">
input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">

执行:

$ ruby -w t.rb 
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">\n"
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">"

我不确定这是否是正确的解决方案,因为我不知道您的输入。是XML吗?使用适当的XML库可能会更好。它更复杂吗?也许输入必须用语法解析。见www.antlr4.org和http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference。本书的源代码是免费的,包含解析XML的语法。

希望有所帮助。乙