DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Tag Cloud - Ruby Class

Snippets Manager user avatar by
Snippets Manager
·
Sep. 05, 08 · · Code Snippet
Like (0)
Save
Tweet
483 Views

Join the DZone community and get the full member experience.

Join For Free
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

Cloud

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • After COVID, Developers Really Are the New Kingmakers
  • Synchronization Methods for Many-To-Many Associations
  • Use Lambda Function URL To Write a Serverless App Backed by DynamoDB
  • Datafaker: An Alternative to Using Production Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo