0

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}"

1 Answer 1

1

Double check your logic. To build an array of unique elements, you want to add each element to the new array unless the new array already includes the element. Ruby let's you write this logic pretty much verbatim:

new_array << number unless new_array.include? number
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The more I learn Ruby the cooler I think this language is, it really does have a human-readable solution for nearly everything! Thanks so much for the help @Max!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.