Using a Regexp in String#gsub in C

Hi,

I’ve got some code in C that makes a call to String#gsub via rb_funcall

VALUE pattern = rb_str_new2(" “);
VALUE heading = rb_funcall(str, rb_intern(“gsub”), 2, pattern,
rb_str_new2(”-"));

I’d like to get pattern to be a Regexp object so that I can replace
repeating whitespace, but the various things I’ve tried so far haven’t
worked. I’ve tried:

VALUE pattern = rb_str_new2("/\s\+/");

and

VALUE pattern = RREGEXP(rb_str_new2("\s\+"))’

Would someone out there be able to help me out with this?

Thanks

You can create the string first (without slashes), then create the
regexp using the string, finally call gsub as usual, passing the regexp
value.

For example:

VALUE pattern = rb_str_new2(“some-pattern”);
VALUE regex = rb_reg_new_str(pattern, 0);

Hope that helps,
Ammar

On Thu, Aug 1, 2013 at 1:58 PM, Ammar A. [email protected] wrote:

Perfect, thanks!

Matt

On Thu, Aug 1, 2013 at 3:41 PM, Ryan D. [email protected]
wrote:

Why not just use rb_reg_new ?

10003 % ag rb_reg_new include/
include/ruby/intern.h
635:VALUE rb_reg_new_str(VALUE, int);
636:VALUE rb_reg_new(const char *, long, int);

That’s even better. Thanks!

On Aug 1, 2013, at 11:58 , Ammar A. [email protected] wrote:

You can create the string first (without slashes), then create the regexp using
the string, finally call gsub as usual, passing the regexp value.

For example:

VALUE pattern = rb_str_new2(“some-pattern”);
VALUE regex = rb_reg_new_str(pattern, 0);

Why not just use rb_reg_new ?

10003 % ag rb_reg_new include/
include/ruby/intern.h
635:VALUE rb_reg_new_str(VALUE, int);
636:VALUE rb_reg_new(const char *, long, int);