Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

ruby on rails - Any way to avoid using gsub! for replacement

I am running in issue, where I used following code.

  def replace_variables(url, project)
    variables = define_variables(project)
    variables.each do |key, value|
      url.gsub!(key, value_encode(value))
    end
    url
  end

And issue was coming due to gsub! usage it was going up and effecting all data, where I just wanted to change data here. so I came to following solution but it is not good, any other way to do it. As it is too much variable definitions. This is working fine, but seem extra variable definitions!

  def replace_variables(url, project)
    variables = define_variables(project)
    temp_url = url
    variables.each do |key, value|
      temp_url = temp_url.gsub(key, value_encode(value))
    end
    temp_url
  end

More explaination Code creating some variables and replacing it from url and change values of it, but I have array of forms and if this runs first it changes those forms value too! which I don't want. The above code working fine but look bad as I am defining accumulator variable and iteration, is there any other way to do it elegantly. I have following define method

  def define_variables(project)
    {
        'TODAYS_DATE' => Date.current.to_s,
        'USER_NAME' => username,
        'PROJECT_NAME' => project.name || '',
     
    }
  end
question from:https://stackoverflow.com/questions/65851726/any-way-to-avoid-using-gsub-for-replacement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If #define_variables returns a key/value hash then something like this should work.

def replace_variables(url, project)
  define_variables(project).inject(url) do |memo, (key, value)|
    memo.gsub(key, value_encode(value))
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...