Convert a array of string

I have a array of strings [“U1,U2”, “U3,U4”, “U2,U1”, “U1,U5”]

I want to remove the duplicate pairs

and also sort on the basis of their 0th index in alphabetical order

like [“U1,U2”, “U1,U5”,“U3,U4”]

uniq will remove duplicates from an array, and sort will sort it into order.
https://docs.ruby-lang.org/en/2.7.0/Array.html#method-i-uniq
https://docs.ruby-lang.org/en/2.7.0/Array.html#method-i-sort

2.7.0 :002 > [1,4,3,3,2,1,4].uniq.sort
 => [1, 2, 3, 4]

But first you have to decide how you are treating your strings → should these also be arrays which you must sort before comparing?

It could be done “quick” by sorting each element first and then by calling uniq on the collection of sorted pairs, as @pcl told you.

But I suggest you to work with a better data structure than a string to represent the pair “U1,U2”.

One data structure that doesn’t care about the order of the elements is the set. So I suggest to get first an array or collection of sets.

Then uniq will remove the repeated sets.
Or you can create a set from that data, that would result in the “same”.

Lastly, reconstruct your strings.

This would be my processing:

["U1,U2", "U3,U4", "U2,U1", "U1,U5"]
  .map { _1.split(',')}  # -> [["U1", "U2"], ["U3", "U4"], ["U2", "U1"], ["U1", "U5"]]
  .map { Set.new(_1)  }  # -> [#<Set: {"U1", "U2"}>, #<Set: {"U3", "U4"}>, #<Set: {"U2", "U1"}>, #<Set: {"U1", "U5"}>]
  .then { Set.new(_1) }  # -> #<Set: {#<Set: {"U1", "U2"}>, #<Set: {"U3", "U4"}>, #<Set: {"U1", "U5"}>}>
  .map(&:sort)           # -> [["U1", "U2"], ["U3", "U4"], ["U1", "U5"]]
  .sort                  # -> [["U1", "U2"], ["U1", "U5"], ["U3", "U4"]]
  .map { _1.join(',') }  # -> ["U1,U2", "U3,U4", "U1,U5"]

Notice how only the first and last lines use those strings “U1,U2”, and the rest of the lines uses Tuples and Sets. You can thing on the first and last line as the interface of this computation, and the rest as the internals. Onions everywhere!!!