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

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

    You can also accomplish this by chaining methods... which might only be of academic interest for this problem, but is still a good technique to be familiar with.

    irb(main):017:0> sh = {}
    => {}
    irb(main):018:0> aers.collect{|k| k.size}.uniq!.each{|k| sh[k] = aers.select{|j| j.size == k}}
    => [1, 2, 3]
    irb(main):019:0> sh
    => {1=>["a", "b", "c", "d"], 2=>["ab", "bc", "de"], 3=>["abc"]}
    irb(main):020:0> 
    

提交回复
热议问题