简体   繁体   中英

Ruby remove interpolation from string

I want to remove string interpolation for eval.

I have a lot of places with such code, so only one option is modifying the condition to unescape code.

I found a regexp that works well

"\#{user.name}"[/[^\#{}]+/]

as result, I have "user.name"

but such code removing curly braces in blocks as well

"\#{[1,2,3].map { |el| el }.join(',')}"[/[^\#{}]+/]

returns

"[1,2,3].map "

the expected result is:

"[1,2,3].map { |el| el }.join(',')"

Any ideas how to solve it?

You can use gsub and named regex in this case

> reg = Regexp.new('\\#{(?<content>.+)}')
=> /\#{(?<content>.+)}/
> str1.gsub(reg) { |match| $~[:content] }
=> "user.name"
> str2.gsub(reg) { |match| $~[:content] }
=> "[1,2,3].map { |el| el }.join(',')"

Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.

BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.

It's better to use proper lexer & parser for more complex cases.

Also, be very... very careful doing eval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM