gpt4 book ai didi

Ruby 在哈希中插入键值元素

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:07 27 4
gpt4 key购买 nike

我想将元素添加到我的哈希列表中,该列表可以有多个值。这是我的代码。不知道怎么解决!

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

非常感谢。

问候,

cocoa

最佳答案

我想这就是你想要做的

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 在哈希中插入键值元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com