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

Tag Cloud - Ruby Class

DZone's Guide to

Tag Cloud - Ruby Class

·
Free Resource
Create a Tag Cloud in Ruby. It's a port of a PHP Class I used to use.
It works.


# TagCloud
#
# Create a Tag Cloud from a string of words
# - fernyb
#
#   cloud = TagCloud.new("a very long string with many word")
#   cloud.klass = "css-Class"
#   puts cloud.build 
#
class TagCloud
  attr_accessor :klass
  
  def initialize(words)
    @wordcount = count_words(words)
  end
  
  def count_words(words)
    wordcount = {}
    words.split(/\s/).each do |word| 
      word.downcase!
      if word.strip.size > 0
        unless wordcount.key?(word.strip)
          wordcount[word.strip] = 0
        else
          wordcount[word.strip] = wordcount[word.strip] + 1
        end
      end
    end
    wordcount
  end
  
  def font_ratio(wordcount={})
    min, max = 1000000, -1000000
    wordcount.each_key do |word|
      max = wordcount[word] if wordcount[word] > max
      min = wordcount[word] if wordcount[word] < min
    end
    18.0 / (max - min)
  end
  
  def build
    cloud = String.new
    ratio = font_ratio(@wordcount)
    @wordcount.each_key do |word|
      font_size = (9 + (@wordcount[word] * ratio))
      cloud << %Q{
  
   #{word} }
    end
    cloud
  end
end


  
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}