class Foo
attr_reader :size, :color
VALID_COLORS = ["small",nil,"medium","large","super-sized"]
VALID_SIZES = ["green", nil, "blue", "red" ]
def size_pos
VALID_COLORS.index(size) || -1
end
def color_pos
VALID_SIZES.index(color) || -1
end
def initialize(opts={})
@size=opts[:size]
@color=opts[:color]
end
def <=>(other)
[size_pos,color_pos] <=> [other.size_pos, other.color_pos]
end
end
foo1 = Foo.new( size: 'large', color: 'blue' )
foo2 = Foo.new( size: 'small' )
foo3 = Foo.new( color: 'green' )
foo4 = Foo.new( size: 'small', color: 'red' )
[foo1,foo2,foo3,foo4].sort
#[#<Foo:0x000000020848d0 @size="small", @color=nil>,
#<Foo:0x00000002065700 @size="small", @color="red">,
#<Foo:0x00000002074868 @size=nil, @color="green">,
#<Foo:0x0000000208da98 @size="large", @color="blue"> ]
您可以通过将位置提取到类变量散列或常量中来提高性能,而不是每次都调用索引。