How to push keys and values into an empty hash w/ Ruby?

前端 未结 2 1333
长情又很酷
长情又很酷 2021-02-05 18:51

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

2条回答
  •  情书的邮戳
    2021-02-05 19:37

    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.

提交回复
热议问题