performance - How to efficiently sort on 2 string attributes, either of which may be nil, in Ruby? -
class foo attr_reader :size, :color def <=> ... foo1 = foo.new( size: 'large', color: 'blue' ) foo2 = foo.new( size: 'small' ) foo3 = foo.new( color: 'green' ) foo4 = foo.new( size: 'small', color: 'red' ) ...
size ordered small, nil, medium, large, super-sized. color ordered green, nil, blue, red.
how efficiently sort first size, color?
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"> ]
you improve performance extracting out positions class variable hash or constant instead of calling index each time.
Comments
Post a Comment