Created
July 18, 2017 09:44
-
-
Save igaiga/58abe028148ad1a7235c3c46265c5518 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h = {} | |
["a", "a", "b"].each do |x| | |
h[x] = [] unless h[x] | |
h[x] << x | |
end | |
p h | |
#=> {"a"=>["a", "a"], "b"=>["b"]} |
h = {}
["a", "a", "b"].each do |x|
(h[x] ||= []) << x
end
とかですかねー。地味ですが 😅
h = Hash.new{|h, k| h[k] = []}
["a", "a", "b"].each do |x|
h[x] << x
end
p h
#=> {"a"=>["a", "a"], "b"=>["b"]}
うわー、たくさんのご回答ありがとうございます!
twitterでの回答
いっくんさんとえむさんのコンストラクタ使うパターン。ko1さんもこのパターンですね。
https://twitter.com/alpaca_tc/status/887284633536086017
Hash.new { |h, k| h[k] = [] }
hidaqaさん、よしだあつしさんのgroup_byパターン。まったく発想になかった。
https://twitter.com/hidaqa/status/887442669969874944
p ["a", "a", "b"].group_by {|x| x }
私は h = Hash.new([].dup)
で書けるのかなと思って書いてみたのですが、思った通り動かなくて質問した、という流れでした。
# 想定とは違った
h = Hash.new([].dup)
p h["a"].object_id #=> 70343972755460
h["a"] << "a"
p h["a"].object_id #=> 70343972755460
h["a"] << "a"
p h["a"] #=> ["a", "a"]
p h #=> {} #←?
# 想定通り
h = Hash.new{|h, k| h[k] = []}
p h["a"].object_id #=> 70278001603780
h["a"] << "a"
p h["a"].object_id #=> 70278001603780
h["a"] << "a"
p h["a"] #=> ["a", "a"]
p h #=> {"a"=>["a", "a"]} #←わかる
default_proc
で代入すると意図していないところでも勝手に追加されるので、追加するところで代入するとか
h["a"] <<= "a"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
キレイかどうかは別として
つまりは、default_procを使うのではどうでしょう。