-2

我有一个代码:

require 'pp'

def unquote_string(string)
    if (string.is_a?(String))
        string.gsub(/\\/,'')
    else 
        string
    end
end

def filter_array_with_substitution_and_replacement(array,options={})
    pp options
    return array unless %w(filterRegex substitudeRegex replacementExpression).any? {|key| options.has_key? key}
    puts "I will substitude!"
    filterRegex = options["filterRegex"]
    substitudeRegex = options["substitudeRegex"]
    replacementExpression = options["replacementExpression"]
    pp "I have: #{replacementExpression}"
    array.select{|object| 
        object =~ filterRegex
    }.map!{|object| 
        object.sub!(substitudeRegex,unquote_string(replacementExpression))
    }
end


def sixth_function
    array = %w(onetwo onethree onefour onesix none any other)
    filterRegex = /one/
    substitudeRegex = /(one)(\w+)/
    replacementExpression = '/#{$2}.|.#{$1}/'
    options = {
        "filterRegex" => filterRegex,
        "substitudeRegex" => substitudeRegex,
        "replacementExpression" => replacementExpression
    }   
    filter_array_with_substitution_and_replacement(array,options)
    pp array
end

def MainWork
   sixth_function()
end

MainWork()

输出:

{"filterRegex"=>/one/,
 "substitudeRegex"=>/(one)(\w+)/,
 "replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
smb192168164:Scripts mac$ ruby rubyFirst.rb
{"filterRegex"=>/one/,
 "substitudeRegex"=>/(one)(\w+)/,
 "replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
["/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "none",
 "any",
 "other"]

这是不正确的,因为带有替换的字符串引用了元字符。如何更正取消引用此字符串replacementExpression

替换后数组的所需输出:

["two.|.one/",
 "three.|.one/",
 "four.|.one/",
 "six.|.one/",
 "none",
 "any",
 "other"]
4

1 回答 1

1

忘了unquote_string——你只是想让你replacementExpression成为'\2.|.\1'

"onetwo".sub(/(one)(\w+)/, '\2.|.\1')
#=> "two.|.one"
于 2014-03-05T14:48:57.523 回答