The object of my coding exercise is to get rid of duplicates in an array without using the uniq method. Here is my code:
numbers = [1, 4, 2, 4, 3, 1, 5]
def my_uniq(array)
sorted = array.sort
count = 1
while count <= sorted.length
while true
sorted.delete_if {|i| i = i + count}
count += 1
end
end
return sorted
end
- When I run this, I get an infinite loop. What is wrong?
- Can I use
deletethe way that I am doing withcount? - How will it execute? Will
countcontinue until the end of the array before the method iterates to the next index? - I did this with
eachormap, and got the same results. What is the best way to do this usingeach,delete_if,map, or awhileloop (with a second loop that compares against the first one)?
while count <= sorted.lengthnever gets looked at.numbers.each_with_object({}) { |n,h| h.update(n=>:anything) }.keys #=>[1, 4, 2, 3, 5]. This requires Ruby v1.9+, which keeps hash keys in insertion order. It relies on the fact that hashes have unique keys.count. Also, the block insorted.delete_if {|i| i = i + count}refers to indexes, but you to compare values.