From: Florian Frank Date: 2002-06-24T23:59:04+09:00 Subject: Re: No exceptions from String#to_i Am 2002-06-24 21:23:58 +0900 schrieb ts: > >>>>> "N" == Nikodemus Siivola writes: > > N> Integer(nil) == 0 > > nil.to_i is defined > > N> Integer(false) #-> exception > > false.to_i is not defined > > N> Array(foo) == foo.to_a > > Well, first ruby look if #to_ary exist and call it otherwise it try to > call #to_a > > N> Integer(foo) != foo.to_i > N> Float(foo) != foo.to_f > > it depend of foo There are exceptions to this rule: Float(nil) => 0.0 object.c: case T_NIL: return rb_float_new(0.0); But nil.to_f throws an exception because it isn't defined. Someone posted an RCR on Ruby Garden concerning this issue: http://www.rubygarden.org/article.php?sid=241 This small patch adds the to_f-method to NilClass: Index: object.c =================================================================== RCS file: /src/ruby/object.c,v retrieving revision 1.79 diff -u -r1.79 object.c --- object.c 2002/05/21 05:39:19 1.79 +++ object.c 2002/06/24 14:49:46 @@ -338,6 +338,13 @@ } static VALUE +nil_to_f(obj) + VALUE obj; +{ + return rb_float_new(0.0); +} + +static VALUE nil_to_s(obj) VALUE obj; { @@ -1072,9 +1079,6 @@ case T_STRING: return rb_float_new(rb_str_to_dbl(val, Qtrue)); - case T_NIL: - return rb_float_new(0.0); - default: return rb_convert_type(val, T_FLOAT, "Float", "to_f"); } @@ -1282,6 +1286,7 @@ rb_cNilClass = rb_define_class("NilClass", rb_cObject); rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0); + rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0); rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0); rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0); rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0); I don't know if this breaks any existing code. -- To assert that the earth revolves around the sun is as erroneous as to claim that Jesus was not born of a virgin. -- Cardinal Bellarmine, "The trial of Galileo", 1615