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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Berger, Daniel (Guest)
on 2006-03-13 18:36
(Received via mailing list)
> -----Original Message-----
> From: removed_email_address@domain.invalid [mailto:removed_email_address@domain.invalid]
> 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

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



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" :
	else {
	    return Qnil;
    return rb_funcall(val, m, 0);

    VALUE val;
    VALUE tmp;

    switch (TYPE(val)) {
      case T_FLOAT:
	if (RFLOAT(val)->value <= (double)FIXNUM_MAX
	    && RFLOAT(val)->value >= (double)FIXNUM_MIN) {
	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);

    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.