to_str in string.c # rb_str_to_str()

T

Timothy Byrd

I have a Bignum object and I tried calling StringValueCStr() to get it
in string form. This raises:

(eval): cannot convert Bignum into String (TypeError)

I believe this is ultimately because this routine in string.c is being
called:

VALUE
rb_str_to_str(str)
VALUE str;
{
return rb_convert_type(str, T_STRING, "String", "to_str");
}

Why is to_str used here? Should it be to_s, since only a few classes
seem to have to_str?

-- Timothy
 
C

Charles Mills

Timothy said:
I have a Bignum object and I tried calling StringValueCStr() to get it
in string form. This raises:

(eval): cannot convert Bignum into String (TypeError)

I believe this is ultimately because this routine in string.c is being
called:

VALUE
rb_str_to_str(str)
VALUE str;
{
return rb_convert_type(str, T_STRING, "String", "to_str");
}

Why is to_str used here? Should it be to_s, since only a few classes
seem to have to_str?

-- Timothy

No, it should be to_str. All objects implement to_s since all classes
are decendents of Object which implements to_s. to_str is reserved for
objects that behave like a string. So if you implemented your own
special string class (take your pick
http://www.and.org/vstr/comparison.html) then you should implement
to_str (and to_str should convert an instance of your string class into
a Ruby String object).

Use rb_String(num) or rb_big2str(num, 10).

-Charlie
 
T

Timothy Byrd

Use rb_String(num) or rb_big2str(num, 10).

I would like to get the string representation of an arbitrary Ruby
object. (The Bignum was just a specific example.)

Thanks for the pointer to rb_String(). It isn't mentioned in my
README.EXT, which says, on the contrary:

***

To get char* from a VALUE, version 1.7 recommend to use new macros
StringValue() and StringValuePtr(). StringValue(var) replaces var's
value to the result of "var.to_str()". StringValuePtr(var) does same
replacement and returns char* representation of var. These macros
will skip the replacement if var is a String. Notice that the macros
requires to take only lvalue as their argument, to change the value
of var in the replacement.

***

I read that as saying that StringValue() and StringValuePtr() (and thus
StringValueCStr()) should work on any type of object. I wouldn't have
guessed they only worked on string-type objects.

Thanks,

-- Timothy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top