将ruby hash .default设置为列表 [英] Setting ruby hash .default to a list

查看:62
本文介绍了将ruby hash .default设置为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果一个键不存在,给一个键的默认值:

  irb(main):001:0> a = {} 
=> {}
irb(main):002:0> a.default = 4
=> 4
irb(main):003:0> a [8]
=> 4
irb(main):004:0> a [9] + = 1
=> 5
irb(main):005:0> a
=> {9 => 5}

一切都好。

但是,如果我将默认设置为空列表或空散列,我不明白它在全部 ....上的行为。

  irb(main):001:0> a = {} 
=> {}
irb(main):002:0> a.default = []
=> []
irb(main):003:0> a [8]<< 9
=> [9]#太好了!
irb(main):004:0> a
=> {}#?!会预期{8 => [9]}
irb(main):005:0> a [8]
=> [9]#真棒!
irb(main):006:0> a [9]
=> [9]#unawesome!这不应该是[]?

我希望/期待与使用|| =操作符相同的行为...

  irb(main):001:0> a = {} 
=> {}
irb(main):002:0> a [8] || = []
=> []
irb(main):003:0> a [8]<< 9
=> [9]
irb(main):004:0> a
=> {8 => [9]}
irb(main):005:0> a [9]
=>无

任何人都可以解释发生了什么吗?

解决方案

Hash.default 用于设置默认值返回不存在。这个集合中的条目并不是为你创建的,只是因为查询它而已。



另外,你设置的值 default to是一个对象的实例(在你的情况下是一个Array),所以当它返回时,它可以被操纵。

  a = {} 
a.default = []#将默认设置为一个新的空数组
a [8]<< 9#a [8]不存在,所以Array实例被返回,并且9追加到它
a.default#=> [9]
a [9]#a [9]不存在,所以默认返回


I thought I understood what the default method does to a hash...

Give a default value for a key if it doesn't exist:

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = 4
=> 4
irb(main):003:0> a[8]
=> 4
irb(main):004:0> a[9] += 1
=> 5
irb(main):005:0> a
=> {9=>5}

All good.

But if I set the default to be a empty list, or empty hash, I don't understand it's behaviour at all....

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = []
=> []
irb(main):003:0> a[8] << 9
=> [9]                          # great!
irb(main):004:0> a
=> {}                           # ?! would have expected {8=>[9]}
irb(main):005:0> a[8]
=> [9]                          # awesome!
irb(main):006:0> a[9]
=> [9]                          # unawesome! shouldn't this be [] ??

I was hoping/expecting the same behaviour as if I had used the ||= operator...

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a[8] ||= []
=> []
irb(main):003:0> a[8] << 9
=> [9]
irb(main):004:0> a
=> {8=>[9]}
irb(main):005:0> a[9]
=> nil

Can anyone explain what is going on?

解决方案

Hash.default is used to set the default value returned when you query a key that doesn't exist. An entry in the collection is not created for you, just because queried it.

Also, the value you set default to is an instance of an object (an Array in your case), so when this is returned, it can be manipulated.

a = {}
a.default = []     # set default to a new empty Array
a[8] << 9          # a[8] doesn't exist, so the Array instance is returned, and 9 appended to it
a.default          # => [9]
a[9]               # a[9] doesn't exist, so default is returned

这篇关于将ruby hash .default设置为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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