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

后端 未结 3 592
太阳男子
太阳男子 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:26

    Ruby has anticipated your need, and has got you covered with Enumerable#group_by:

    irb(main):001:0> aers = %w(a b c d ab bc de abc)
    #=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
    
    irb(main):002:0> aers.group_by{ |s| s.size }
    #=> {1=>["a", "b", "c", "d"], 2=>["ab", "bc", "de"], 3=>["abc"]}
    

    In Ruby 1.9, you can make this even shorter with:

    irb(main):003:0> aers.group_by(&:size)
    #=> {1=>["a", "b", "c", "d"], 2=>["ab", "bc", "de"], 3=>["abc"]}
    

提交回复
热议问题