2009-12-02 32 views
2

如果我有兩個數組ab,包含的對象必須覆蓋哪種方法,這樣減法-才能正常工作?需要什麼方法讓「 - 」(減法)方法與Ruby數組一起工作?

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 

但是這是行不通的,因爲ab被關押在數組中。我想知道我需要在我的課程中重寫什麼方法才能正常工作。

+0

你能定義「正常工作」嗎?現在,從array1中減去array2,可以刪除array2中存在的任何項目。我想這似乎是預期的效果。 – 2009-12-02 03:31:54

+0

@dcneiner:對於每一個對象? ...我正在定義...讓我把這個問題 – OscarRyz 2009-12-02 03:34:39

回答

4

您需要重新定義#eql?hash方法。

你可以將其定義爲:

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

詳情:

要看看什麼東西被稱爲紅寶石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] 
    => [] 

同樣是在紅寶石真正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] 
    => [] 
+0

mmhh讓我們看... ruby​​ -version:我有1.8.7 :( – OscarRyz 2009-12-02 03:42:55

+0

呃...... :)我認爲這有點太先進了我只是還沒有.....讓我咀嚼它一段時間;) – OscarRyz 2009-12-02 04:06:54

+0

好的,我做了'def hash'幷包括這個:'id.has + 32 * desc.hash',但它仍然不起作用。我錯過了什麼? – OscarRyz 2009-12-02 04:12:39

相關問題