2

如果我有两个数组aand b,包含的对象应该重写什么方法,以便减法方法-正常工作?

够了吗eql?

编辑

我正在为我的问题添加更多细节。

我定义了这个类:

class Instance
    attr_reader :id, :desc 
    def initialize( id ,  desc  )
        @id = id.strip
        @desc = desc.strip
    end

    def sameId?( other )
        @id == other.id
    end

    def eql?( other )
        sameId?( other ) and @desc == other.desc
    end

    def to_s()
        "#{id}:#{desc}"
    end
end

好的?

然后我从不同的部分填充了我的两个数组,我想得到不同。

a = Instance.new("1","asdasdad")
b = Instance.new("1","a")
c = Instance.new("1","a")

p a.eql?(b) #false
p b.eql?(c) #true 

x = [a,b]
y = [c]

z = x - y # should leave a because b and c "represent" the same object

但这不起作用,因为aandb被保存在数组中。我想知道我需要在我的类中重写什么方法才能使其正常工作。

4

1 回答 1

4

您需要重新定义#eql?散列方法。

您可以将其定义为:

def hash
    id.hash + 32 * desc.hash
end

细节:

要查看 Ruby 1.9 中调用了什么:

    % irb
    >> class Logger < BasicObject
    >>   def initialize(delegate)
    >>     @delegate = delegate
    >>   end
    >>   def method_missing(m,*args,&blk)
    >>     ::STDOUT.puts [m,args,blk].inspect
    >>     @delegate.send(m,*args,&blk)
    >>   end
    >> end
    => nil
    >> object = Logger.new(Object.new)
    [:inspect, [], nil]
    => #<Object:0x000001009a02f0>
    >> [object] - [0]
    [:hash, [], nil]
    [:inspect, [], nil]
    => [#<Object:0x000001009a02f0>]
    >> zero = Logger.new(0)
    [:inspect, [], nil]
    => 0
    >> [zero] - [0]
    [:hash, [], nil]
    [:eql?, [0], nil]
    => []

在 ruby​​ 1.8.7 中也是如此

    % irb18
    >> class Logger < Object
    >>   instance_methods.each { |m| undef_method m }
    >>   def initialize(delegate)
    >>     @delegate = delegate
    >>   end
    >>   def method_missing(m,*args,&blk)
    >>     ::STDOUT.puts [m,args,blk].inspect
    >>     @delegate.send(m,*args,&blk)
    >>   end
    >> end
    (irb):2: warning: undefining `__send__' may cause serious problem
    (irb):2: warning: undefining `__id__' may cause serious problem
    => nil
    >> object = Logger.new(Object.new)
    [:inspect, [], nil]
    => #<Object:0x100329690>
    >> [object] - [0]
    [:hash, [], nil]
    [:inspect, [], nil]
    => [#<Object:0x100329690>]
    >> zero = Logger.new(0)
    [:inspect, [], nil]
    => 0
    >> [zero] - [0]
    [:hash, [], nil]
    [:eql?, [0], nil]
    => []
于 2009-12-02T03:41:40.183 回答