在 Ruby 中,为了创建数组的散列并将元素推送到这些数组,我见过两种习惯用法。我想知道人们更喜欢哪一个,为什么。 (披露:我有自己的看法,但我想确保我没有遗漏一些明显的东西。)
方法 1:使用 Hash 的花式初始化器:
ht = Hash.new {|h,k| h[k]=[]}
ht["cats"] << "Jellicle"
ht["cats"] << "Mr. Mistoffelees"
当您使用尚不存在的键访问 ht 时,此方法会创建一个空数组。
方法 2:简单的初始化器,花哨的访问器:
ht = {}
(ht["cats"] ||= []) << "Jellicle"
(ht["cats"] ||= []) << "Mr. Mistoffelees"
人们对哪一个更好(或者哪一个优于另一个)有意见吗?
最佳答案
有时散列最初是用数据填充的,后来它只用于检索数据。在那些情况下,我更喜欢第一种可能性,因为可以“清空”默认过程(在 Ruby 1.9 中)。
ht = Hash.new {|h,k| h[k]=[]}
ht["cats"] << "Jellicle"
ht["cats"] << "Mr. Mistoffelees"
ht["dogs"]
p ht
#=> {"cats"=>["Jellicle", "Mr. Mistoffelees"], "dogs"=>[]}
ht.default_proc = proc{}
ht["parrots"] #nil
p ht
#=> {"cats"=>["Jellicle", "Mr. Mistoffelees"], "dogs"=>[]} No parrots!
关于ruby - 将元素插入 ruby Hash 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5009295/