Ruby Inserting Key, Value elements in Hash

后端 未结 2 1764
别那么骄傲
别那么骄傲 2021-02-08 01:15

I want to add elements to my Hash lists, which can have more than one value. Here is my code. I don\'t know how I can solve it!

class dictionary

  def initializ         


        
2条回答
  •  误落风尘
    2021-02-08 01:33

    I think this is what you're trying to do

    class Dictionary
      def initialize()
        @data = Hash.new { |hash, key| hash[key] = [] }
      end
      def [](key)
        @data[key]
      end
      def []=(key,words)
        @data[key] += [words].flatten
        @data[key].uniq!
      end
    end
    
    d = Dictionary.new
    d['tall'] = %w(long word1 word2)
    d['something'] = %w(anything foo bar)
    d['more'] = 'yes'
    
    puts d.inspect
    #=> #["long", "word1", "word2"], "something"=>["anything", "foo", "bar"], "more"=>["yes"]}>
    
    puts d['tall'].inspect
    #=> ["long", "word1", "word2"]
    

    Edit

    Now avoids duplicate values thanks to Array#uniq!.

    d = Dictionary.new
    d['foo'] = %w(bar baz bof)
    d['foo'] = %w(bar zim)     # bar will not be added twice!
    
    puts d.inspect
    #["bar", "baz", "bof", "zim"]}>
    

提交回复
热议问题