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?
开发者_Python百科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
if your class is a collection that implements 'each'
you can mixin Enumerable 
to get a slew of methods including 'include?'
Are you saying the array is an instance variable?
class Foo
  def my_array_include?(obj)
    @my_array.include?(obj)
  end
end
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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论