Sha256: 877a45df758b31f1c1ff05229b2e3413b36e7b61acbf21e93409da9f6b516766

Contents?: true

Size: 1.95 KB

Versions: 6

Compression:

Stored size: 1.95 KB

Contents

#
# After a HashMap example
# by Daniel Shiffman.
#
# This example demonstrates how to use a Hash to store
# a collection of objects referenced by a key. This is much like an array,
# only instead of accessing elements with a numeric index, we use a String.
# If you are familiar with associative arrays from other languages,
# this is the same idea.
#
# The Processing classes IntHash, FloatHash, and StringHash offer a simple
# way of pairing Strings with numbers or other Strings. But are probably of
# less interest to rubyists.
#
# In this example, words that appear in one book (Dracula) are colored white
# whilst words in the other book (Frankenstein) are colored black.
#
load_library 'word'

DRACULA = 'dracula.txt'
FRANKENSTEIN = 'frankenstein.txt'
DRAC = /#{DRACULA}/
FRANK = /#{FRANKENSTEIN}/

attr_accessor :words

def setup
  size(640, 360)

  # Create the HashMap
  @words = {}
  # Load two files
  load_file(DRACULA)
  load_file(FRANKENSTEIN)
  # Create the font
  text_font(create_font('Georgia', 24))
end

def draw
  background(126)
  # Show words
  words.values.each do |w|
    if w.qualify?
      w.display
      w.move
    end
  end
end

# Load a file
def load_file(filename)
  tokens = File.open(data_path(filename), 'r'){ |file| file.read.scan(/[\w'-]+/)}
  tokens.each do |s|
    s = s.downcase
    # Is the word in the HashMap
    if (words.key?(s))
      # Get the word object and increase the count
      # We access objects from a Hash via its key, the String
      w = words[s]
      # Which book am I loading?
      if DRAC =~ filename
        w.increment_dracula
      elsif FRANK =~ filename
        w.increment_franken
      end
    else
      # Otherwise make a new word
      w = Word.new(s)
      # And add entry to the Hash
      # The key for us is the String and the value is the Word object
      words[s] = w
      if DRAC =~ filename
        w.increment_dracula
      elsif FRANK =~ filename
        w.increment_franken
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ruby-processing-2.6.3 samples/processing_app/topics/advanced_data/word_frequency.rb
ruby-processing-2.6.2 samples/processing_app/topics/advanced_data/word_frequency.rb
ruby-processing-2.6.1 samples/processing_app/topics/advanced_data/word_frequency.rb
ruby-processing-2.6.0 samples/processing_app/topics/advanced_data/word_frequency.rb
ruby-processing-2.5.1 samples/processing_app/topics/advanced_data/word_frequency.rb
ruby-processing-2.5.0 samples/processing_app/topics/advanced_data/word_frequency.rb