Ruby 想问一个 Hash default 方法的问题

bysxiang · October 09, 2016 · Last by mizuhashi replied at October 10, 2016 · 2234 hits
h = Hash.new('java')
h[:a] = 33

h.default() #=> 'java'

h.default(:a) #=> 'java'
h.default(:b) #=> 'java'

按 Ruby 文档说法,default() 不提供参数,或参数 (key) 不存在时,返回默认值。key 存在,返回键对应的值。

可结果却不一样,这是 bug 吗?ruby-2.0.0-p648, ruby-2.3 都是一样的结果

If obj is specified, this single object will be used for all default values

所以要用 block 的形式:

Hash.new { |h, k| h[k] = 'java' }

好像确实是文档与实现不一致饿,,, =。=

.default(:a) 哈希是这样存取的?

[1] pry(main)> h = Hash.new('java')
=> {}
[2] pry(main)> h[:a] = 33
=> 33
[3] pry(main)> h
=> {:a=>33}
[4] pry(main)> h.default(:a)
=> "java"
[5] pry(main)> h.default
=> "java"
[6] pry(main)> h[:b]
=> "java"
[7] pry(main)> h[:a]
=> 33
[8] pry(main)> h[:c]
=> "java"

#3 楼 @mizuhashi 这是获取默认值的。

Supplemental notes

To clarify: When called with no argument, it returns the default value. When called with a hash key it returns the corresponding value for that key if the hash contains that key. Only if the key does not exist does it return the default value.

官方原文,。。。。郁闷

#1 楼 @tony612 这样来看,default(key = nil),不知道还要这参数干嘛。

#7 楼 @bysxiang 默认值可以是代码块,要代入 key 求值

bysxiang closed this topic. 10 Oct 13:42
You need to Sign in before reply, if you don't have an account, please Sign up first.