Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns a complex which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.
'9'.to_c           #=> (9+0i)
'2.5'.to_c         #=> (2.5+0i)
'2.5/1'.to_c       #=> ((5/2)+0i)
'-3/2'.to_c        #=> ((-3/2)+0i)
'-i'.to_c          #=> (0-1i)
'45i'.to_c         #=> (0+45i)
'3-4i'.to_c        #=> (3-4i)
'-4e2-4e-2i'.to_c  #=> (-400.0-0.04i)
'-0.0-0.0i'.to_c   #=> (-0.0-0.0i)
'1/2+3/4i'.to_c    #=> ((1/2)+(3/4)*i)
'ruby'.to_c        #=> (0+0i)
See Kernel.Complex.
               static VALUE
string_to_c(VALUE self)
    char *s;
    VALUE num;


    s = RSTRING_PTR(self);

    if (s && s[RSTRING_LEN(self)]) {
        s = RSTRING_PTR(self);
        s[RSTRING_LEN(self)] = '\0';

    if (!s)
        s = (char *)"";

    (void)parse_comp(s, 0, &num);

    return num;

Was this page useful?