Forum: Ruby Re: Integer(nil) and checking numericality

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F3b7b8756d0c7f71cc7460cc33aefaee?d=identicon&s=25 Berger, Daniel (Guest)
on 2006-03-13 17:36
(Received via mailing list)
> -----Original Message-----
> From: eastcoastcoder@gmail.com [mailto:eastcoastcoder@gmail.com]
> Sent: Thursday, March 09, 2006 8:19 PM
> To: ruby-talk ML
> Subject: Integer(nil) and checking numericality
>
>
> Why does Integer(nil) return 0?  Isn't the point of Integer
> to assert that the arg is actually an integer?  (If we just
> want a best guess, we can do '323aaadsfwefsd'.to_i or ''.to_i )/

Not exactly.  It normally returns the value that YourObject#to_int would
return.  However, it makes special checks for Floats, Numeric types and
Strings.  In some cases, such as nil, it returns the value of .to_i
instead.

Below is the relevant source (from object.c) if you want the nitty
gritty.

Regards,

Dan

static VALUE
convert_type(val, tname, method, raise)
    VALUE val;
    const char *tname, *method;
    int raise;
{
    ID m;

    m = rb_intern(method);
    if (!rb_respond_to(val, m)) {
	if (raise) {
	    rb_raise(rb_eTypeError, "can't convert %s into %s",
		     NIL_P(val) ? "nil" :
		     val == Qtrue ? "true" :
		     val == Qfalse ? "false" :
		     rb_obj_classname(val),
		     tname);
	}
	else {
	    return Qnil;
	}
    }
    return rb_funcall(val, m, 0);
}

VALUE
rb_Integer(val)
    VALUE val;
{
    VALUE tmp;

    switch (TYPE(val)) {
      case T_FLOAT:
	if (RFLOAT(val)->value <= (double)FIXNUM_MAX
	    && RFLOAT(val)->value >= (double)FIXNUM_MIN) {
	    break;
	}
	return rb_dbl2big(RFLOAT(val)->value);

      case T_FIXNUM:
      case T_BIGNUM:
	return val;

      case T_STRING:
	return rb_str_to_inum(val, 0, Qtrue);

      default:
	break;
    }
    tmp = convert_type(val, "Integer", "to_int", Qfalse);
    if (NIL_P(tmp)) {
	return rb_to_integer(val, "to_i");
    }
    return tmp;
}
This topic is locked and can not be replied to.