如何循环输入数组并通过使用 Ruby 向其推送项目来构建输出数组

How do you loop through an input array and build an output array by pushing items on it using Ruby

我正在学习 class,其中一个问题需要我们构建一个 ruby 脚本。在脚本中定义一个方法调用 unique,它将接受一个数组参数。然后让该方法从数组中删除重复项。 (例如:unique([1,2,3,2,1,6,9]) 会 return [1,2,3,6,9])。我们必须实现一个使用 array.uniq 方法的版本,并实现一个不使用该方法的版本;此版本将遍历输入数组并通过在其上推送项目来构建输出数组,具体取决于数组中是否为 included?

这是我到目前为止所写的。有3种方法。第一个使用 array.uniq 并按预期运行。第二个是尝试使用 .include?,但它 return 显然是数组中的所有数字。不确定我在那里做了什么......第三个是在黑暗中拍摄的一种方式来查看数字是否被重复,如果是,则不要将其添加到 test_array.

任何人都可以帮助这个新人找出我做错了什么以及我应该做什么吗?提前谢谢大家!

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

仔细检查你的逻辑。要构建唯一元素的数组,您需要将每个元素添加到新数组 ,除非新数组已经包含该元素。 Ruby 让我们逐字逐句地编写此逻辑:

new_array << number unless new_array.include? number