Search code examples
rubyquotesmetacharacters

Passing replacement string as parameter


I have a code:

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()

Output:

{"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"]

It is not correct, because string with replacement have metacharacters quoted. how to correct unquote this string replacementExpression?

Desired output for array after replacement:

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

Solution

  • Forget unquote_string - you simply want your replacementExpression to be '\2.|.\1':

    "onetwo".sub(/(one)(\w+)/, '\2.|.\1')
    #=> "two.|.one"