Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Add An Array Of Hash Tags To A String

DZone's Guide to

Add An Array Of Hash Tags To A String

·
Free Resource
This method adds an array of hash tags to a given string, as many as possible, in order. It returns a new string of up to 140 characters, unless the original string was 140 characters or longer, in which case the original string is returned. Useful for automated Twitter status updates.

def hash_tag(str, tags)
  while tags && str.length < 140 && tags.length > 0
    tag = tags.shift
    if (str.length + tag.length) < 139
      str << " \##{tag}"
    end
  end
  str
end

Example: A short string and a few short tags.

hash_tag('A short string.', ['tag1', 'tag2', 'tag3'])
=> "A short string. #tag1 #tag2 #tag3"
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}