HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Changing URLs into HTML links

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
intolinkschanginghtmlurls

Problem

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 &:first
  new_string = string.clone

  matches.each do |match|
    new_string.gsub! match, "#{ match }"
  end

  new_string
end


How can I refactor to remove the new_string? Any other suggestions?

Solution

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|
      "#{ match }"
    end || str # Return str if no match
  end
end


In console:

> str = "this is a test abc.com"
> result = autolink_string str
=> "this is a test abc.com"
> str
=> "this is a test abc.com"
> result
=> "this is a test abc.com"

> autolink_string "no url here"
=> "no url here"

> autolink_string ""
=> ""

> autolink_string "this is a test abc.com and test twitter.com"
=> "this is a test abc.com and test twitter.com"

Code Snippets

def autolink_string str
  unless str.empty?
    regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
    str.clone.gsub!(regex) do |match|
      "<a href='http://#{ match }'>#{ match }</a>"
    end || str # Return str if no match
  end
end
> str = "this is a test abc.com"
> result = autolink_string str
=> "this is a test <a href='http://abc.com'>abc.com</a>"
> str
=> "this is a test abc.com"
> result
=> "this is a test <a href='http://abc.com'>abc.com</a>"

> autolink_string "no url here"
=> "no url here"

> autolink_string ""
=> ""

> autolink_string "this is a test abc.com and test twitter.com"
=> "this is a test <a href='http://abc.com'>abc.com</a> and test <a href='http://twitter.com'>twitter.com</a>"

Context

StackExchange Code Review Q#26427, answer score: 2

Revisions (0)

No revisions yet.