This works, but there may be a more efficient way to do it - feel free to chime in with suggestions, I'm new!
[1,2,2,2,3,4,5,6,6,6,6].group_by{|x| x}.sort_by{|k,v| -v.size}[0..4][0..4].map{|arr| arr[0] }
Groups the values, sorts by the size of the groups, then extracts the topic_ids from the resulting arrays. Result is an array of topic_ids sorted by frequency.