Building Hash by grouping array of objects based on a property of the items

后端 未结 3 590
太阳男子
太阳男子 2021-02-05 07:53

I\'m wondering if there is a more canonical way to do this in ruby 1.9

I have an array with a bunch of objects and I want to group them into a Hash using a property of e

3条回答
  •  野性不改
    2021-02-05 08:21

    Phrogz is correct, group_by is there for the taking. Your code contains one of ruby's gotcha's.

    aers = %w(a b c d ab bc de abc)
    sh = Hash.new([]) # returns the _same_ array everytime the key is not found. 
    # sh = Hash.new{|h,v| h[v] = []}  # This one works
    p sh, sh.default
    
    aers.each do |aer|
      sh[aer.size] << aer  #modifies the default [] every time
    end
    p sh, sh.default
    p sh[5]
    

    Output

    {}
    []
    {}
    ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
    ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
    

提交回复
热议问题