在Ruby中,最有效的方法之一去重數組是通過使用uniq
方法。這將返回一個新的數組,其中刪除了重復的元素,同時保持了元素的原始順序。以下是一個例子:
array = [1, 2, 3, 1, 2, 4, 5, 6, 4, 7]
unique_array = array.uniq
puts unique_array.inspect
# 輸出: [1, 2, 3, 4, 5, 6, 7]
如果你需要根據對象的屬性去重,可以使用uniq
方法結合塊。例如,假設你有一個Person
類,并且你想要根據name
屬性去重:
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
people = [
Person.new("Alice", 30),
Person.new("Bob", 25),
Person.new("Alice", 30),
Person.new("Eve", 28)
]
unique_people = people.uniq { |person| person.name }
puts unique_people.inspect
# 輸出: [
# #<Person:0x00007f981d7c90 @name="Alice", @age=30>,
# #<Person:0x00007f981d7b80 @name="Bob", @age=25>,
# #<Person:0x00007f981d7a70 @name="Eve", @age=28>
# ]
在這個例子中,uniq
方法通過傳遞一個塊來根據name
屬性去重,同時保持了Person
對象的原始順序。