4

カスタム定義の class があり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'エントリの 1 つが によって削除されることを期待しています.uniqが、出力にはまだエントリが繰り返されています。

次のように、クラス定義にメソッドを==追加しようとしました。eql?

def ==(other)
    other.class == self.class && other.date == self.date && other.group == self.group && other.time == self.time
end
alias :eql? :==

しかし、それもうまくいきませんでした...助けて!

4

2 に答える 2

3

の 2 つのインスタンスが、、の値を共有している場合でも、それらの ID が異なるため、の使用はuniq機能しませんでした。それ自体のインスタンスではなく、これらのインスタンス変数の値を比較する必要があります。Instruction@date@group@timeInstruction

instructions.uniq{|e| [e.date, e.group, e.time]}
于 2013-02-28T16:01:30.573 に答える
3

オーバーライドするのを忘れましたhash。同じ値eql?を持つオブジェクトに対してのみ呼び出されます。hash

于 2013-03-01T02:31:55.650 に答える