Changing URLs into HTML links This method changes all URLs in the string into an HTML link. The goal is to not mutate the string passed in, which I believe is a good practice.

The new_string code in this method does not seem idiomatic.

def autolink_string string
  return    if string.nil? 
  return '' if string.empty?

  regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
  groups = string.scan regex
  matches = groups.map &amp;:first
  new_string = string.clone

  matches.each do |match|
    new_string.gsub! match, "&lt;a href='http://#{ match }'&gt;#{ match }&lt;/a&gt;"
  end

  new_string
end


How can I refactor to remove the new_string? Any other suggestions?
You can use gsub! and block directly with a clone.

def autolink_string str
  unless str.empty?
    regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
    str.clone.gsub!(regex) do |match|
      "&lt;a href='http://#{ match }'&gt;#{ match }&lt;/a&gt;"
    end || str # Return str if no match
  end
end


In console:

&gt; str = "this is a test abc.com"
&gt; result = autolink_string str
=&gt; "this is a test &lt;a href='http://abc.com'&gt;abc.com&lt;/a&gt;"
&gt; str
=&gt; "this is a test abc.com"
&gt; result
=&gt; "this is a test &lt;a href='http://abc.com'&gt;abc.com&lt;/a&gt;"

&gt; autolink_string "no url here"
=&gt; "no url here"

&gt; autolink_string ""
=&gt; ""

&gt; autolink_string "this is a test abc.com and test twitter.com"
=&gt; "this is a test &lt;a href='http://abc.com'&gt;abc.com&lt;/a&gt; and test &lt;a href='http://twitter.com'&gt;twitter.com&lt;/a&gt;"