我将自己的方法添加到Array类中,该类与Array#uniq完全相同。
这是我的版本:
arr = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]
class Array
def my_uniq
new_arr = []
each do |item|
new_arr << item unless new_arr.include?(item)
end
new_arr
end
end
print arr.my_uniq
有没有办法修改它来返回唯一元素的索引而不是元素本身?
答案 0 :(得分:0)
each_with_index
将允许您迭代数组并返回索引。
-
答案 1 :(得分:0)
class Array
def indices_uniq
uniq.map { |e| index(e) }
end
end
arr = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]
arr.indices_uniq
#=> [0, 1, 2, 3, 6, 7]
要了解这里发生了什么,让我们更详细地写一下,并包含一些显示中间值的代码:
class Array
def indices_uniq
puts "self = #{self}"
arr = self
u = arr.uniq
puts "u = #{u}"
u.map { |e|
puts "#{e} is at index #{index(e)}"
arr.index(e) }
end
end
arr.indices_uniq
# self = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]
# u = ["fun", "sun", 3, 5, 1, 2]
# fun is at index 0
# sun is at index 1
# 3 is at index 2
# 5 is at index 3
# 1 is at index 6
# 2 is at index 7
#=> [0, 1, 2, 3, 6, 7]
我们可以替换u
和arr
:
class Array
def indices_uniq
self.uniq.map { |e| self.index(e) }
end
end
arr.indices_uniq
#=> [0, 1, 2, 3, 6, 7]
密钥: self
是没有显式接收方的方法的接收方。方法的最后一个版本uniq
和include
都有显式接收者self
。因此,如果删除显式接收器,接收器仍然是self
:
class Array
def indices_uniq
uniq.map { |e| index(e) }
end
end
arr.indices_uniq
#=> [0, 1, 2, 3, 6, 7]
另一种方法是将操作线更改为:
map { |e| index(e) }.uniq