我的编码练习的目的是在不使用该uniq
方法的情况下消除数组中的重复项。这是我的代码:
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
delete
的方式count
吗?count
在方法迭代到下一个索引之前,将继续到数组末尾吗?each
或进行了此操作map
,并得到了相同的结果。什么是做到这一点使用的最佳方式each
,delete_if
,map
,或while
环(与第二环是比较反对的第一个)?问题是内部循环是一个无限循环:
while true
sorted.delete_if {|i| i = i + count}
count += 1
end #while
您可能可以做您正在做的事情,但这并不能消除重复项。
一种方法是:
numbers = [1, 4, 2, 4, 3, 1, 5]
target = []
numbers.each {|x| target << x unless target.include?(x) }
puts target.inspect
将其添加到数组类中:
class ::Array
def my_uniq
target = []
self.each {|x| target << x unless target.include?(x) }
target
end
end
现在您可以执行以下操作:
numbers = [1, 4, 2, 4, 3, 1, 5]
numbers.my_uniq
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句