0

So I have this string

x = "{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}" 

and I want to replace the rocket symbol that is beside a character to a pipe symbol. so the result is

x = "{"1"=>"test","2"=>"Another|Test","3"=>"Another|One"}" 

I have this code right now

if x =~ /(=>\w)/).present?
    x.match(/=>\w/) do |match|
      #loop through matches and replace => with |
    end
end

So basically my question is how do I loop through a matched by regex and replace the rocket sign to a pipe?

7
  • 3
    That string looks like the string representation of a Ruby hash. Where do you get the string from? I did you consider working on the original Ruby hash? Commented Mar 7, 2019 at 17:26
  • gsub will let you replace parts of string by regex Commented Mar 7, 2019 at 17:26
  • @SergioTulentsev yes but I dont want to replace =>T to | I just wanted to replace => to a | if it matches the regex /=>\w/ Commented Mar 7, 2019 at 17:30
  • @stuckoverflow24: ah, I see. In this case, you could use a positive lookahead (assert presence without including it in the match). Look it up. Commented Mar 7, 2019 at 17:31
  • 1
    I'm specifically asking for the code in your question to match, exactly, what you're trying to deal with. Right now that's not valid Ruby code. Commented Mar 7, 2019 at 18:01

1 Answer 1

2

gsub with a positive look-ahead will do it.

x = %q[{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}]
x.gsub!(%r{=>(?=\w)}, '|')
puts x

A look-ahead (or look-behind) matches, but does not include that bit in the match.

Though I think %r{=>(?=[^"])}, a => which is not in front of a quote, is more correct.

x = %q[{"1"=>"what about => a space?","2"=>"Or=>(this)"}]
x.gsub!(%r{=>(?=[^"])}, '|')
puts x
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.