我有一个自定义类Instruction
。实例被初始化并收集在一个数组中。有一些重复的(所有实例变量相同)实例,我想将它们过滤掉。
class Instruction
attr_accessor :date, :group, :time
def initialize(date, group, time)
@date, @group, @time = date, group, time
end
end
instructions = Array.new
instructions.push ( Instruction.new('2000-01-01', 'Big', '10am') )
instructions.push ( Instruction.new('2000-01-01', 'Small', '9am') )
instructions.push ( Instruction.new('1999-09-09', 'Small', '4pm') )
instructions.push ( Instruction.new('2000-01-01', 'Small', '9am') )
instructions.uniq.each {|e| puts "date: #{e.date} \tgroup: #{e.group} \ttime: #{e.time}"}
我希望其中一个'2000-01-01', 'Small', '9am'
条目被 删除.uniq
,但是我仍然在输出中看到重复的条目。
我尝试向类定义中添加==
和eql?
方法,如下所示:
def ==(other)
other.class == self.class && other.date == self.date && other.group == self.group && other.time == self.time
end
alias :eql? :==
但这也不起作用……救命!