user1245233
user1245233

Reputation: 45

Remove braces in Ruby

I want to remove the braces so "{test}" becomes "test". I tried

"{test}".gsub(/\{(.*)\}/,$1)
while "{test}".gsub!(/(\{).*(\})/,""); end
"{test}".gsub(/\{.*\}/,"")  

Nothing seems to work.

Upvotes: 2

Views: 4500

Answers (4)

Gagan Gami
Gagan Gami

Reputation: 10251

Try with String#tr

> "{test}".tr '{}', ''
#=> "test"

Upvotes: 0

sohaibbbhatti
sohaibbbhatti

Reputation: 2682

I'm assuming you want to remove all curly brackets from a given statement. In that case please try

"{test}".gsub(/\{|\}/, '')   => "test" 

On the other hand if you want to remove curly brackets from the beginning or the hand you can perhaps do it using a non-regex based way

Upvotes: 2

Stefan
Stefan

Reputation: 114248

You have to use \1, not $1

"{test}".gsub /\{(.*)\}/, '\1'

Or, if you just want to delete all curly braces:

"{test}".delete "{}"

Upvotes: 11

marian craciunescu
marian craciunescu

Reputation: 11

You could use the delete function.

           static VALUE
rb_str_delete(int argc, VALUE *argv, VALUE str)
{
str = rb_str_dup(str);
rb_str_delete_bang(argc, argv, str);
return str;
 }
        example:
"hello".delete "l" =>"heo"

Upvotes: 1

Related Questions