From: Neil Conway Date: 2001-09-09T05:52:59+09:00 Subject: [ruby-talk:21015] Re: length of Ruby array from C? On Sat, 2001-09-08 at 16:22, David Alan Black wrote: > Hello -- > > On Sun, 9 Sep 2001, Neil Conway wrote: > > I've been experimenting with writing some Ruby extensions in C. In order > > to find the length of a Ruby array, I needed to do this: > > > > /* -------- */ > > VALUE ary; > > int ary_length; > > /* ... assign a Ruby array to "ary" ... */ > > ary_length = RARRAY(ary)->len; > > /* -------- */ > > > > There are 2 problems with this, IMHO: > > > > 1) undocumented: I had to look through the source to find this > > It's described in README.EXT, section 1.3: Woops, sorry about that. I had been using the Pickaxe book, which doesn't document this. Thanks for the information. > > 2) clumsy: if this is the only way to get the length, could we perhaps > > have some syntactic sugar? For instance, a function (or macro) > > rb_ary_length(VALUE), which returns the length of the specified array as > > a C integer. Since this is a relatively common operation, I think it > > would be worthwhile to make it a bit easier for extension writers. > > I think that would be sort of unwieldy, since you'd have to have > rb_ary_xxxx(VALUE), rb_string_xxxx(VALUE), etc., to replace the > current way of doing it by accessing C structure members. I still think this would be a good idea. Of the builtin structs, 'length' only makes sense for RArray and RString. You _could_ add functions for RRegexp, RBigNum and RStruct, but since these are relatively rarely used (compared to RArray and RString), there would be no need to define more than 2 functions -- rb_ary_len(VALUE) and rb_str_len(VALUE). That's not too unwieldy, IMHO; and I find "rb_ary_len(ary)" to be more readable than "RARRAY(ary)->len". It also prevents extension writers from (directly) accessing the fiels of those structures, which is generally a bad idea (as README.EXT points out). Cheers, Neil