I suggest you write your class as follows.
class Words
@words = {}
# @words is a class instance variable, generally a better choice than a class
# variable because it cannot be seen from subclasses. It is a hash, with keys
# being words and values being the associated instances of this class.
singleton_class.public_send(:attr_reader, :words)
# This creates a read accessor for the class instance variable @words.
attr_reader :definitions
# this creates a read accessor for @definitions, which returns an array
# of one or more definitions that have been given for the word.
def initialize(word)
@definitions = []
self.class.words[word] = self
# self.class => Words, Word.words is the hash of words and their instances.
# The key-value pair `word=>self` is being added to that hash.
end
def add_definition(definition)
@definitions << definition
end
def self.remove_definition(word)
words.delete(word)
end
# This is a class method used to remove words from the dictionary.
end
Let's try it.
word = Words.new("bridle")
#=> #<Words:0x00005d1850124740 @word="bridle", @definitions=[]>
word.add_definition "the headgear used to control a horse."
word.add_definition "show one's resentment or anger."
word.definitions
#=> ["the headgear used to control a horse.",
# "show one's resentment or anger."]
Words.words
#=> {"bridle"=>#<Words:0x000059addb793410 @definitions=[
# "the headgear used to control a horse.",
# "show one's resentment or anger."]>}
word = Words.new("cheesy")
#=> #<Words:0x00005d18501a8dd8 @word="cheesy", @definitions=[]>
word.add_definition "like cheese in taste, smell, or consistency."
word.add_definition "cheap, unpleasant, or blatantly inauthentic."
word.definitions
#=> ["like cheese in taste, smell, or consistency.",
# "cheap, unpleasant, or blatantly inauthentic."]
Words.words
#=> {"bridle"=>#<Words:0x000059addb793410 @definitions=[
# "the headgear used to control a horse.",
# "show one's resentment or anger."]>,
# "cheesy"=>#<Words:0x000059addb527be0 @definitions=[
# "like cheese in taste, smell, or consistency.",
# "cheap, unpleasant, or blatantly inauthentic."]>}
Words.words.keys
#=> ["bridle", "cheesy"]
Words.words["cheesy"].definitions
#=> ["like cheese in taste, smell, or consistency.",
# "cheap, unpleasant, or blatantly inauthentic."]
Words.remove_definition("bridle")
Words.words
#=> {"cheesy"=>#<Words:0x000059addb527be0 @definitions=[
# "like cheese in taste, smell, or consistency.",
# "cheap, unpleasant, or blatantly inauthentic."]>}
As an exercise I suggest you add instance methods remove_definition
and change_definition
, each with an argument that is an index position in the array of definitions for the given word.