Substituindo o operador de naves espaciais da Ruby <=>
-
27-09-2019 - |
Pergunta
Estou tentando substituir o operador de Ruby (Spaceship) para classificar maçãs e laranjas para que as maçãs venham primeiro classificadas em peso e laranjas em segundo lugar, classificadas por doçura. Igual a:
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
Mas isso não funciona, alguém pode dizer o que estou fazendo de errado aqui, ou uma maneira melhor de fazer isso?
Solução
Seu problema é que você está apenas inicializando uma das propriedades de ambos os lados, a outra ainda será nil
. nil
não é tratado no Array#<=>
Método, que acaba matando o tipo.
Existem algumas maneiras de lidar com o problema primeiro seria algo assim
[self.weight.to_i, self.sweetness.to_i] <=> [other.weight.to_i, other.sweetness.to_i]
nil.to_i
da-te 0
, o que deixará este trabalho.
Outras dicas
Provavelmente tarde, no entanto ...
Adicione o seguinte Monkeypatch
class Array
def to_i(default=Float::INFINITY)
self.map do |element|
element.nil? ? default : element.to_i
end
end
end
E mudar o corpo de Fruity::<=> to
[self.weight, self.sweetness].to_i <=> [other.weight, other.sweetness].to_i