Topic: Multiple .gsub refactoring

Anybody know of a cleaner way to do this?

text = text.gsub('[PROJECT_NAME]', @project_name)
text = text.gsub('[CLIENT_NAME]', @client_name)
text = text.gsub('[PROJECT_LINK]', @project_link)
return text

Re: Multiple .gsub refactoring

If it's only three, that's probably about the easiest it's going to get. If you want to refactor it to be more generic, you could do something like this:

%w(project_name client_name project_link).each do |var|
  text.gsub!("[#{var.upcase}]", instance_variable_get("@#{var}"))
end
return text

That's no shorter for just three (and certainly a bit more cryptic), but it is a more general solution if you want to have more variables.

(P.S. If you want to expose all instance variables this way, you could do it like this:

instance_variables.each do |var|
  text.gsub!("[#{var[1..-1].upcase}]", instance_variable_get(var))
end
return text

But that, obviously, probably exposes many things unnecessarily.)

Last edited by manitoba98 (2008-09-09 16:01:51)