2009-12-02 3 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에있는 array1의 모든 항목이 제거됩니다. 나는 그것이 원하는 효과라고 생각합니다. –

+0

@dcneiner : 모든 개체에 대해? ... 나는 정의 중입니다 ... 질문에 넣으십시오. – OscarRyz

답변

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

+0

uhh ... :) 그게 너무 진보 된 것 같아요. 나를 아직 잠시 씹어 둡시다.) – OscarRyz

+0

좋아요, 나는'def hash '를했고'id.has + 32 * desc.hash'를 포함 시켰지만 여전히 작동하지 않습니다. 내가 뭘 놓치고 있니? – OscarRyz

관련 문제