加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails源代码:以奇怪的方式初始化哈希?

发布时间:2020-12-17 03:35:18 所属栏目:百科 来源:网络整理
导读:在rails源: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb 以下可以看出 @load_hooks = Hash.new {|h,k| h[k] = [] } 在IRB中只是初始化一个空哈希.这样做有什么不同 @load_hooks = Hash.new 解决方法
在rails源: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb

以下可以看出

@load_hooks = Hash.new {|h,k| h[k] = [] }

在IRB中只是初始化一个空哈希.这样做有什么不同

@load_hooks = Hash.new

解决方法

看看 ruby documentation for Hash

new → new_hash click to toggle source
new(obj) → new_hash
new {|hash,key| block } → new_hash

Returns 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.
Example form the docs

# While this creates a new default object each time
h = Hash.new { |hash,key| hash[key] = "Go Fish: #{key}" }
h["c"]           #=> "Go Fish: c"
h["c"].upcase!   #=> "GO FISH: C"
h["d"]           #=> "Go Fish: d"
h.keys           #=> ["c","d"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读