0

is there a way to use the spaceship method and the magic "method_missing" in one class? The below example gives me undefined method '<' whenever I try foo1 < foo2 with a definiton like:

class Foo

  def initialize(params)
    @parent= params[:parent]
  end

  def <=>(o)
     ...
  end

  def method_missing(sym, *args, &block)
    @parent.send sym, *args, &block
  end
end

Any help appreciated :)

pagid
  • 13,559
  • 11
  • 78
  • 104

2 Answers2

6

short answer:

You're missing this line of code inside Foo:

include Comparable

long answer:

You don't get the <, >, <=, etc. methods just by redefining the spaceship operator.

You get those methods by including Comparable. Those methods then use the spaceship operator to provide a valid response.

It's more or less what happens with Enumerable:

you include the module, implement the each method, and then get all the other methods (map, select, etc) for "free".

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
1

I'm not sure I understand what your question is. For the < and > methods to be created, put include Comparable in your class definition and define the <=> instance method.

Kudu
  • 6,570
  • 8
  • 27
  • 27