我有一个类,其中数据存储为一个集合,我希望能够比较该类的对象,以便元素的字母大小写无关紧要。例如,如果集合包含字符串元素,则"a"
和应该没有区别"A"
。
为此,我尝试将eql?
set 成员的方法定义为不区分大小写,但这对Set 中的方法-
(别名)没有影响。difference
那么,我应该如何对-
大小写不敏感呢?
下面的代码说明了这个问题:
require 'set'
class SomeSet
include Enumerable
def initialize; @elements = Set.new; end
def add(o)
@elements.add(o)
self
end
def each(&block) # To enable +Enumerable+
@elements.each(&block)
end
def difference(compared_list)
@elements - compared_list
end
end
class Element
attr_reader :element
def initialize(element); @element = element; end
# This seems to have no effect on +difference+
def eql?(other_element)
element.casecmp(other_element.element) == 0
end
end
set1 = SomeSet.new
set2 = SomeSet.new
set1.add("a")
set2.add("A")
# The following turns out false but I want it to turn out true as case
# should not matter.
puts set1.difference(set2).empty?