05 - keeping multiple values for the same hash key.rb
来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 25 行
RB
25 行
hash = Hash.new { |hash, key| hash[key] = [] }raw_data = [ [1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, ['b', 'c']], [3, 'c'] ]raw_data.each { |x,y| hash[x] << y }hash # => {1=>["a", "b", "c"], 2=>["a", ["b", "c"]], 3=>["c"]}#---class MultiValuedHash < Hash def []=(key, value) if has_key?(key) super(key, [value, self[key]].flatten) else super end endendhash = MultiValuedHash.newraw_data.each { |x,y| hash[x] = y }hash# => {1=>["c", "b", "a"], 2=>["b", "c", "a"], 3=>"c"}#---
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?