hash.rb
h = Hash.new{ |h,k| h[k] = "fuga: #{k}" }
h["c"]
p h
何が返ってくると思いますか?
What do you think will return?
{"c" => "fuga: c"}
なんです。
Above is what you will get.
クールですね!
Isn't it cool?
下記のように、パラメータを伴ったメソッド呼び出しをメモ化 したいときに使えるそうです!
You could use this to memoize your function which takes a paramter.
memoization.rb
def top_cities(order_by)
@top_cities ||= Hash.new do |h, key|
h[key] = where(top_city: true).order(key).to_a
end
@top_cities[order_by]
end
出典/Originally written in
http://www.justinweiss.com/blog/2014/07/28/4-simple-memoization-patterns-in-ruby-and-one-gem/