Ruby: How to group a Ruby array?

后端 未结 6 1304
执念已碎
执念已碎 2020-12-28 12:17

I have a Ruby array

> list = Request.find_all_by_artist(\"Metallica\").map(&:song)
=> [\"Nothing else Matters\", \"Enter sandman\", \"Enter Sandman         


        
6条回答
  •  -上瘾入骨i
    2020-12-28 12:42

    Late but clean answer I have,

    l = list.group_by(&:titleize)
    l.merge(l) { |k,v| l[k] = v.count }
    

    Note: If we do want unique keys i.e. without titleize, then replace it with itself

提交回复
热议问题