tags:

views:

60

answers:

3

I want to define method like include?(obj) which check existence of obj in array of my class. Is there a way to do this in ruby?

I have Item class

class Item < ActiveRecord::Base
    include Comparable

    belongs_to :itemable, :polymorphic => true
    def <=>(other)
      self.itemable.id <=> other.itemable.id
    end
...
end

and I want to use it this way

item_set1.subset? item_set2

but it turns out not using <=> in the process and using only item.id to check. How to override subset or other ways to get this done.

Thanks

+1  A: 

Are you saying the array is an instance variable?

class Foo
  def my_array_include?(obj)
    @my_array.include?(obj)
  end
end
Matchu
+3  A: 

if your class is a collection that implements 'each'
you can mixin Enumerable to get a slew of methods including 'include?'

Chris Hulan
A: 

Set uses eql? and hash, not == or <=>. Try this:

class Item < ActiveRecord::Base

  ...

  def eql?(other)
    id == other.id
  end

  def hash
    id
  end

end
Wayne Conrad
those subset? method use eql? and hash to determine the equivalent ?Thanks
art
That's correct. Set requires that the things stored in it have eql? and hash defined in a way that makes sense. By default, Object.eql? and Object.hash test for "is the same Ruby object." Above, we redefine them to mean "refers to the same database object." Now all Set operations, including subset?, will work for you.
Wayne Conrad