开发者

ruby hash setup

I found this in my some code I was working on 开发者_JAVA技巧and I was wondering what this is doing

h = Hash.new {|hash, key| hash[key] = 0}
 => {} 


When a block is passed to Hash.new that block is called each time a non-existent key is accessed. Eg:

h = Hash.new { |hash, key| hash[key] = "Default" }
h[:defined_key] = "Example"    

puts h[:defined_key] # => "Example"
puts h[:undefined_key] # => "Default"

See http://ruby-doc.org/core/classes/Hash.html#M000718 for more detail.


http://ruby-doc.org/core/classes/Hash.html#M000718

This block defines what the hash does when accessing a nonexistent key. So if there is no value for a key, then it sets the value to 0, and then returns 0 as the value.

It's not just good for defaults - you could have it throw an exception of there is no such key, for example. In fact, if you just want a default value, you can say:

Hash.new "defaultValue"


Its making the default values for any new keys equal to zero instead of nil, observe the test in and irb console session:

$ irb
>> normal_hash = Hash.new
=> {}
>> normal_hash[:new_key]
=> nil
>> h = Hash.new {|hash, key| hash[key] = 0}
=> {}
>> h[:new_key]
=> 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜