Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created June 18, 2012 19:36
Show Gist options
  • Save kmandreza/2950269 to your computer and use it in GitHub Desktop.
Save kmandreza/2950269 to your computer and use it in GitHub Desktop.
Dictionary
Creating a dictionary class
[This exercise was adapted from TestFirst.org.]
Create a Dictionary class. When you create a new dictionary (such as one for English), it should be an empty hash. Then, you should be able to add words and their definition by calling a method and passing in a hash as an argument. You should also be able to list all of the words and their definitions in alphabetical order with another method. Finally, you should be able to search the dictionary by passing in the first few letters of a word and returning all of the words that start with those letters, along with their definitions.
class Dictionary
attr_accessor :entries
def initialize
@entries = {}
end
def add(entry)
if entry.class == Hash
@entries.merge!(entry)
elsif entry.class == String
@entries[entry] = nil
end
end
def include?(word)
@entries.keys.include?(word)
end
def keywords
@entries.keys.sort
end
def find(word)
@entries.reject {|key,value| !key.start_with?(word)}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment