Home > front end >  Ruby - Iterate through each string inside an array and remove repeated characters
Ruby - Iterate through each string inside an array and remove repeated characters

Time:10-24

I need to take out every duplicate from each string individually, but not from the whole array. Basically what I'm looking for is a .uniq for each string inside the array, but not the array as a whole.

Example:

array = ["abc", "abc", "xxzzyyww", "aaaaa"]

Expected output:

["abc", "abc", "xzyw", "a"]

I tried using array.uniq and array.each.uniq but they are not considering each string individually, they are checking if the string as a whole is a duplicate in the array, so it gives me the following output:

["abc", "ab", "xxzzyyww", "aaaaa"]

CodePudding user response:

What about using string#squeeze (https://apidock.com/ruby/String/squeeze)

array = ["abc", "abc", "xxzzyyww", "aaaaa"]
# => ["abc", "abc", "xxzzyyww", "aaaaa"]

array.map {|x| x.squeeze }
# => ["abc", "abc", "xzyw", "a"]

CodePudding user response:

Input

array = ["abc", "abc", "xxzzyyww", "aaaaa"]

Code

p array.map { _1.chars.uniq.join }

Output

["abc", "abc", "xzyw", "a"]
  • Related