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

前端 未结 2 1334
长情又很酷
长情又很酷 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")
    

提交回复
热议问题