Ruby在Hash中插入Key,Value元素 [英] Ruby Inserting Key, Value elements in Hash

查看:177
本文介绍了Ruby在Hash中插入Key,Value元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加元素到我的哈希列表中,它可以有多个值。这是我的代码。
$ b

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 initialize(publisher)             
    @publisher=publisher
    @list=Hash.new()                    
  end

  def []=(key,value)
    @list << key unless @list.has_key?(key)
    @list[key] = value
  end

end


dic = Dictionary.new

dic["tall"] = ["long", "word-2", "word-3"]

p dic

非常感谢。

问候,

koko

推荐答案

我认为这就是您要做的事情

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
#=> #<Dictionary:0x42d33c @data={"tall"=>["long", "word1", "word2"], "something"=>["anything", "foo", "bar"], "more"=>["yes"]}>

puts d['tall'].inspect
#=> ["long", "word1", "word2"]



编辑



现在通过 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
#<Dictionary:0x42d48c @data={"foo"=>["bar", "baz", "bof", "zim"]}>

这篇关于Ruby在Hash中插入Key,Value元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆