0

I am a beginner trying to learn ruby and I am writing a code for following problem statement: - Create a dictionary which is initially empty. - add entries to it.. the word should be the key and meanings should be values. - add whole entries with keyword and definition (when adding a word, it should check if it already exists) - add keywords without definition (in this case set the definition to be nil) - can check whether a given keyword exists - finds a keyword entry and returns keyword + definition - finds multiple matches from a prefix and returns the entire entry (keyword + definition) - i.e if we search for "fi" then it should return all entries beginning with "fi" - lists keywords alphabetically

So far I have written the following code, but when I am adding keywords and values, it is storing only the last value added. in the following case the output is "@word_list={"great"=>"remarkable"}>". The first set of values were lost.

I dont know how to solve this problem. Any help would be great.Thanks in advance!

class Dictionary

  def word_list
     @word_list = Hash.new
  end

  def add new_entry
    case new_entry
     when Hash
        word_list.merge!(new_entry)
     when String
         word_list[new_entry] = nil
    end
   end


d1 = Dictionary.new
d1.add ({"fish" => "aquatic animal", "fiend" => "bad person"})
d1.add ({"great" => "remarkable"})

puts d1.inspect

1 Answers1

1

Everytime word_list is called you make a new hash, replacing whatever was in @word_list before with an empty hash.

def word_list
  @word_list = Hash.new
end

Try ||= instead, and no reason to use Hash.new here when {} will do fine. Where, of course, a ||= b means a = a || b which will only use the value if the value is as of yet unset.

def word_list
  @word_list ||= {}
end

Or perhaps it would be better to not lazy initialize the @word_list at all since a dictionary without a word list is no dictionary at all. Instead make the internal hash in the initialize method so every instance will always have one.

class Dictionary
  def initialize
    @word_list = {}
  end

  def word_list
    @word_list
  end

  # other methods...
end
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337