Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Last active April 19, 2021 18:27
Show Gist options
  • Save kwilczynski/04d513a1d4af7bc89391835fc07b5d0b to your computer and use it in GitHub Desktop.
Save kwilczynski/04d513a1d4af7bc89391835fc07b5d0b to your computer and use it in GitHub Desktop.
Cleaning up Ruby array in C extension.
#define RSTRING_EMPTY_P(s) (RSTRING_LEN(s) == 0)
static VALUE
magic_strip(VALUE v)
{
return (ARRAY_P(v) || STRING_P(v)) ? \
rb_funcall(v, rb_intern("strip"), 0) : \
Qnil;
}
static VALUE
magic_strip_array(VALUE value) {
VALUE array = rb_ary_new();
VALUE entry = Qundef;
for (int i = 0; i < RARRAY_LEN(value); i++) {
entry = rb_ary_entry(value, i);
if (NIL_P(entry))
continue;
if (STRING_P(entry)) {
if (RSTRING_EMPTY_P(entry))
continue;
entry = magic_strip(entry);
}
rb_ary_push(array, entry);
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment