开发者

How to define ruby method for collection of object?

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜