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

前端 未结 2 1335
长情又很酷
长情又很酷 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:30

    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")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题