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

Time:01-31

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?

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

CodePudding user response:

/\/|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?}, '')
  • Related