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]

0

2 Answers 2

3
a.group_by(&:itself).select{|_, a| a[1]}.keys
Sign up to request clarification or add additional context in comments.

2 Comments

Although a[1] is shorter, I'd use the more explicit a.length > 1. Nice side effect: it works for nil and false values.
yep it's clearly the fastest, here are some benchmarks gist.github.com/equivalent/3c9a4c9d07fff79062a3
2

My colleague suggested this :

a = [1,2,3,2,4,4,2,5]
a.select{ |el| a.count(el) > 1 }.uniq
# => [2,4] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.