I'm taking a class and one of the problems requires us to build a ruby script. In the script define a method call unique, which will accept an argument of an array. Then have the method remove duplicate items from an array. (Example: unique([1,2,3,2,1,6,9]) would return [1,2,3,6,9]). We have to implement a version that uses the array.uniq method and implement one that doesn't; this version will loop through the input array and build an output array by pushing items on it, depending on whether or not it is included? in the array.
This is what I have written so far. There are 3 methods. The first uses the array.uniq and functions as expected. The second is an attempt to use .include?, but it returns all of the numbers in the array, obviously. Not sure what I was doing there... The third was a shot in the dark at a way to see if the number is being duplicated and if it is, not add it to the test_array.
Can anyone help this new guy figure out what I'm doing wrong and what I should be doing? Thank you all in advance!
numbers = [1,2,3,2,1,6,9]
def unique(array)
u_num = array.uniq
puts "These are the numbers in the array #{array} without duplicates: #{u_num}"
end
puts unique(numbers)
#---------------------------------------------------------------------------------
new_array = []
numbers.each do |number|
if numbers.include?(number)
new_array << number
end
end
puts "#{new_array}"
#---------------------------------------------------------------------------------
test_array = []
numbers.each do |number|
if number.detect { |i| numbers }
test_array << i
end
end
puts "#{test_array}"