Ruby we might Miss

Posted on August 9, 2011

0


This is the continuation of the series I started.
The topic for this post :
Hash

——————————————————————————————————————
• Hash.new accepts a block, which provides a way to calculate a default value if the hash
has none. This is useful for caching. The first time a cached method is called with a
particular set of arguments, the block is invoked; it calculates the value and stores it
in the hash for future access. ActiveSupport has an implementation of hash caching in
caching_tools.rb, which generates hashes like this:
Hash.new do |as, a|
as[a] = Hash.new do |bs, b|
bs[b] = slow_method(a, b)
end
end
——————————————————————————————————————

——————————————————————————————————————
Hash#delete removes a value from the hash and returns it. This is useful for stripping
out keyword arguments from a hash before passing it along somewhere.
——————————————————————————————————————

Advertisements
Posted in: Ruby