Overriding Ruby's spaceship operator <=>

Posted by ericsteen1 on Stack Overflow See other posts from Stack Overflow or by ericsteen1
Published on 2010-06-17T04:10:12Z Indexed on 2010/06/17 4:33 UTC
Read the original article Hit count: 206

Filed under:
|
|
|

I am trying to override Ruby's <=> (spaceship) operator to sort apples and oranges so that apples come first sorted by weight, and oranges second, sorted by sweetness. Like so:

module Fruity
  attr_accessor :weight, :sweetness

  def <=>(other)
    # use Array#<=> to compare the attributes
    [self.weight, self.sweetness] <=> [other.weight, other.sweetness]
  end
  include Comparable
end

class Apple
include Fruity

def initialize(w)
  self.weight = w
end

end

class Orange
include Fruity

def initialize(s)
  self.sweetness = s
end

end

fruits = [Apple.new(2),Orange.new(4),Apple.new(6),Orange.new(9),Apple.new(1),Orange.new(22)]

p fruits

#should work?
p fruits.sort

But this does not work, can someone tell what I am doing wrong here, or a better way to do this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby