LoginSignup
6
4

More than 5 years have passed since last update.

Hash.newのクールな初期化方法/Cool Way to initialize your Hash in Ruby

Posted at
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/

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4