Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I remove "/" and "/i" in a returned string with gsub?

I have this line:msg = "Couldn't find column: #{missing_columns.map(&:inspect).join(',')}"

that outputs: Couldn't find column: /firstname/i, /lastname/i

Is there a way that I can use gsub to return only the name of the column without the "/" and "/i"? Or is there a better way to do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried errors = msg.gsub(/\/|i/, '') but it returns the the first missing column with "frstname".

>Solution :

/\/|i/

Let’s break this down. The // on the outside are delimiters, sort of like quotation marks for strings. So the actual regex is on the inside.

\/|i

\/ says to match a literal forward slash. \ prevents it from being interpreted as the end of the regular expression.

i says to match a literal i. So far nothing fancy. But | is an alternation. It says to match either the thing on the left or the thing on the right. Effectively, this removes all slashes and i from your string. You want to remove all / or /i, but not i on its own. You can still do that with alternation, provided you include the slash on both sides.

/\/|\/i/

You can also do it more compactly with the ? modifier, which makes the thing before it optional.

/\/i?/

Finally, you can avoid the /\/ fencepost shenanigans by using the %r{...} regular expression form rather than /.

%r{/i?}

All in all, that’s

errors = msg.gsub(%r{/i?}, '')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading