1

Given you have a Ruby Array like a = [1,2,3,2,4,4,2,5] how can you select elements that occurred multiple times in the given array ?

so return value == [2,4]

equivalent8
  • 13,754
  • 8
  • 81
  • 109

2 Answers2

3
a.group_by(&:itself).select{|_, a| a[1]}.keys
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Although `a[1]` is shorter, I'd use the more explicit `a.length > 1`. Nice side effect: it works for `nil` and `false` values. – Stefan Jul 10 '15 at 14:42
  • yep it's clearly the fastest, here are some benchmarks https://gist.github.com/equivalent/3c9a4c9d07fff79062a3 – equivalent8 Jul 13 '15 at 13:55
2

My colleague suggested this :

a = [1,2,3,2,4,4,2,5]
a.select{ |el| a.count(el) > 1 }.uniq
# => [2,4] 
equivalent8
  • 13,754
  • 8
  • 81
  • 109