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
精彩评论