# Re: Integer(nil) and checking numericality

**URL:** <https://www.ruby-forum.com/t/re-integer-nil-and-checking-numericality/54711>\
**Category:** Ruby\
**Created:** [March 13, 2006, 5:36pm UTC](https://www.ruby-forum.com/t/re-integer-nil-and-checking-numericality/54711 "2006-03-13T17:36:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![BergerS\_Daniel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bc8723/32.png) [@BergerS\_Daniel](https://www.ruby-forum.com/u/BergerS_Daniel)\
**Post date:** [March 13, 2006, 5:36pm UTC](https://www.ruby-forum.com/t/re-integer-nil-and-checking-numericality/54711/1 "2006-03-13T17:36:01Z")

</div>

> -----Original Message-----  
> From: removed\_email\_address@domain.invalid [[mailto: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  
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;

```

}
