Question

I'm trying to remove duplicate numbers from each line in a text file. For some reason, it won't remove the duplicate number 4. If I append an additional number after the 4, it works fine and the duplicate 4's are removed.

def remove_dup(str)
  str.split(",").uniq.join(",")
end

File.open('pad.txt','r').each do |line|
  puts remove_dup(line)
end

My input 'pad.txt' file:

1,1,1,2,2,3,3,4,4
2,3,4,5,5

My output:

1,2,3,4,4
2,3,4,5
Was it helpful?

Solution

Perhaps since you are getting the string from a text file, there is a \n at the end of the string. Hence, the last 4 is actually 4\n.

Try this to see if it works:

def remove_dup(str)
    str.chomp.split(",").uniq.join(",")
end

The chomp method will remove the carriage return characters from the end of the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top