0

I have a variable in Ruby:

A='a\-b'
puts A

it will print out:

a\-b

Without using gsub to directly change content of this variable, how can I get Ruby to print out

a-b

as though as I was doing

A="a\-b"

and put the result in a variable?

  • 2
    Not sure I understand the question. If *"[You] have [this] variable"* then why not just change it from single quotes to double quotes or better yet just remove the backslash that you don't want anyway? Otherwise you are going to have to use one of the String methods for substitution or deletion (does not have to be `gsub`) – engineersmnky Jul 06 '23 at 19:30
  • 2
    PSA: `A` is a constant. `a` is a variable. – tadman Jul 06 '23 at 20:09
  • 2
    Single quotes behave differently than double quotes, in particular how they interpret backslash and `#{` sequences. Think of single quotes as *non-interpolating* quotes, where you will get pretty much what you ask for every time, while double quotes *interpolate* it. – tadman Jul 06 '23 at 20:10
  • 2
    _"Without using gsub to directly change content of this variable"_ – why these restrictions? What is allowed? And what’s the purpose of this conversion? – Stefan Jul 06 '23 at 20:29
  • 3
    You cannot do that. `A='a\-b'` (same as `"a\\-b"`) is a string containing four characters. You wish to print out a string containing three characters. The only way to do that is to remove the unwanted character (here a backslash). – Cary Swoveland Jul 06 '23 at 20:35

1 Answers1

0

What I believe you're asking is to evaluate the escape characters. Something like eval %Q{"#{s}"} or undump

See Best way to escape and unescape strings in Ruby?