From: Nobuyoshi Nakada Date: 2009-09-05T06:49:35+09:00 Subject: [ruby-core:25384] Re: [Feature #1697] Object#<=> Hi, At Sun, 28 Jun 2009 10:48:45 +0900, Marc-Andre Lafortune wrote in [ruby-core:24063]: > Other comparison operators like <, <=, >=, > would also gain > in consistency if they were defined in terms of <=>. This > way, 0 < nil and nil > 0 would raise the same errors instead > of errors of different types. This is secondary to the main > question: is it better to define Object#<=> or not? > My vote is on 'yes'. A patch for it. Index: object.c =================================================================== --- object.c (revision 24752) +++ object.c (working copy) @@ -32,5 +32,5 @@ VALUE rb_cTrueClass; VALUE rb_cFalseClass; -static ID id_eq, id_eql, id_match, id_inspect, id_init_copy; +static ID id_eq, id_eql, id_match, id_inspect, id_init_copy, id_cmp; /* @@ -1116,4 +1116,14 @@ rb_obj_not_match(VALUE obj1, VALUE obj2) } +/* :nodoc: */ +static VALUE +rb_obj_cmp(VALUE obj, VALUE arg) +{ + if (!rb_respond_to(arg, id_cmp)) { + rb_notimplement(); + } + return Qnil; +} + /*********************************************************************** @@ -2518,4 +2528,5 @@ Init_Object(void) rb_define_method(rb_mKernel, "=~", rb_obj_match, 1); rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1); + rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1); rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1); rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); @@ -2659,4 +2670,5 @@ Init_Object(void) id_inspect = rb_intern("inspect"); id_init_copy = rb_intern("initialize_copy"); + id_cmp = rb_intern("<=>"); for (i=0; conv_method_names[i].method; i++) { -- Nobu Nakada