def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal 1,hash1[:one] #ok assert_equal nil,hash1[:two] #ok hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal 1,hash2[:one] #ok assert_equal "dos",hash2[:two] #hm? end
我的猜测是Hash.new(“dos”)使“dos”成为所有不存在键的默认答案.我对吗?
解决方法
new → new_hash
new(obj) → new_hash
new {|hash,key| block } → new_hashReturns a new,empty hash. If this hash is subsequently accessed by a
key that doesn’t correspond to a hash entry,the value returned
depends on the style of new used to create the hash. In the first
form,the access returns nil. If obj is specified,this single object
will be used for all default values. If a block is specified,it will
be called with the hash object and the key,and should return the
default value. It is the block’s responsibility to store the value in
the hash if required.
原文地址:https://www.jb51.cc/ruby/266878.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。