I have a dictionary class and want to be able to push keys (as keywords) and values (as definitions) into an empty hash with an \'add\' method. I don\'t understand how to syntac
Looking at your Rspec, It looks like you need this setup.
class Dictionary
def initialize
@hash = {}
end
def add(key_value)
key_value.each do |key, value|
@hash[key] = value
end
end
def entries
@hash
end
def keywords
@hash.keys
end
end
Do not use key.to_sym
in add method, just key
To give flexibility to add method, I can return the self object to continuesly add.
def add(key_value)
key_value.each do |key, value|
@hash[key] = value
end
self
end
So, I can do this now.
@d.add("a" => "apple").add("b" => "bat")
Instantiate your hash in Dictionary
's initialize
:
class Dictionary
def initialize
@hash = {}
end
def add(defs)
defs.each do |word, definition|
@hash[word] = definition
end
end
end
Right now you have no hash until you call entries
, which you don't.
entries
should return the existing hash, not create a new one.
keywords
should return the hash's keys.
You do not need accessors for keyword
and definition
. Such singular items are meaningless in a dictionary class. You might want something like lookup(word)
that returned a definition.
Also, you convert words to symbols, but I don't know why–particularly since you use string keys in your spec. Pick one, although I'm not convinced this is a case where symbols add value.
Please consider variable naming carefully to provide as much context as possible.