在执行gsub时,在ruby中分配内存(NoMemoryError)

时间:2012-05-24 02:22:32

标签: ruby regex out-of-memory gsub

我有一个使用一些变量替换的js文件,现在我想以相反的方式替换它们。

由于该文件已包含用于替换的'key-value',因此我想首先提取它们然后进行替换。

这是文件(仅作为示例):

.......
//mapperstart
var pj = "shape", qj = "version", rj = "toFixed";  //this line is what I want to find
//mapperend
function (){
    //32[rj](10);
}
......
//mapperstart
var kl = ll = "moveend", ml = "move", nl = "movestart"; //this line is what I want to find
//mapperend
......

我在'key-value'行后添加注释,然后使用以下ruby代码替换:

def replaceVariable(fname)
    content=IO.read(fname);
    key_value={};

    if(matchData=content.scan(/\/\/mapperstart(.+?)\/\/mapperend/m))
        matchData.each do |md|
            md=md[0].gsub(/\s+var\s+/,'').gsub(';','');
            md_ary=md.split(',');
            if(md_ary && md_ary.length>0)
                md_ary.each do |kv|
                    if(kv.include?('='))
                        kv_pair=kv.split('=');
                        key=kv_pair[0].strip;
                        value=kv_pair[1].strip;
                        if(key_value.has_key?(key))
                            puts 'repeat key:'+key
                        else
                        key_value[key]=value
                        end
                    end
                end
            end
        end

        key_value.each do |key,value|
            pattern=Regexp.new('['+key+']');
            content.gsub!(pattern,value);
            puts 'replace:'+key
        end

        ext_name=File.extname(fname);
        puts ext_name
        File.open(fname.gsub(ext_name,'')+"_fix"+ext_name,'aw') do |f|
            f.puts content
        end
    end
end

replaceVariable('../file.js');

但是我总是遇到in 'gsub!': failed to allocate memory (NoMemoryError)错误。

如何解决?

0 个答案:

没有答案