Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate pair values from given array in Ruby?

Tags:

ruby

I want to remove a pair of 'duplicates' from an array of strings, where each element has the form R1,R2, with varying numbers. In my case, a duplicate would be R2,R1 because it has the same elements of R1,R2 but inverted.

Given:

a = ['R1,R2', 'R3,R4', 'R2,R1', 'R5,R6']

The resulting array should be like so:

a = ['R1,R2', 'R3,R4', 'R5,R6']

How could I remove the duplicates so I would have the following?

like image 440
Rajkumar Ulaganadhan Avatar asked Sep 03 '26 03:09

Rajkumar Ulaganadhan


2 Answers

A solution with Set

require 'set' 

a.uniq { |item| Set.new(item.split(",")) }  # => ["R1,R2", "R3,R4", "R5,R6"]
like image 65
Ursus Avatar answered Sep 06 '26 20:09

Ursus


Here is a working example :

array = ['R1,R2', 'R3,R4', 'R2,R1', 'R5,R6']

array.uniq { |a| a.split(',').sort }
like image 20
BTL Avatar answered Sep 06 '26 21:09

BTL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!