I have an array like this:
array = ["john-56", "admin-57", "duke-58", "duke-65",
"john-56", "admin-57", "roger-65", "roger-15"]
I want to keep only the elements that are duplicated, in this case I expect to get this result:
["admin-57","admin-57","john-56","john-56"]
I've tried using the keep_if method like this:
array.keep_if { |x,y| x==y }
But it leaves array empty.
Maybe not the more efficient, but one line:
array.select { |x| array.count(x) == 2 }.uniq
@edit(thanks to Jounty)
If you have values than can appear more than two times
array.select { |x| array.count(x) > 1 }.uniq
Array#keep_if only passes the current element in the iteration.
You could use:
duplicates = array.keep_if { |x| array.count(x) > 1 }.uniq
Or:
duplicates = array.uniq | array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With