0

I have to work with a long text and make some substitution with regexp inside it. Now I wrote the following code:

text = File.read(file)
replacements = [
                [/```([\w]+)/, "\n\1>"],
                [/```\n/, "\n\n"],
                [/pattern not found/, 'sub'],
                [/pattern that should be found/, 'no sub'],
               ]
replacements.inject(text) do |text, (k,v)|
    if text =~ k
        text.gsub!(k,v)
    end
end
File.write(name', text)

If every regexp is found in my document everything works fine, but if a replacements pattern is not found, all subsequent replacements are not carried out.

I put the if text =~ k but it does not work the same.

Any idea?

3 Answers 3

3

The reason is that String#gsub! returns nil if there were no substitutions made, and the result if there were. Another glitch is that you call matching twice, the check for text =~ k is redundant.

I would go with not inplace version of gsub:

result = replacements.inject(text) do |text, (k, v)|
  text.gsub(k, v)
end

the above should do the trick.

Whether you still want to use inplace substitution, you might just return text itself on unsuccessful gsub!:

result = replacements.inject(text) do |text, (k, v)|
  text.gsub!(k, v) || text
end
Sign up to request clarification or add additional context in comments.

Comments

2

Each inject iteration should return memo (in your case text) to the next iteration. Try this code:

replacements.inject(text) do |text, (k,v)|
  if text =~ k
    text.gsub!(k,v)
  end
  text
end

Comments

2

The block of inject must return memo value. So, you may have to change your code to do this:

replacements.inject(text) do |text, (k,v)|
    text.gsub(k,v)
end

When if test =~ k failed in your case, the block's output was nil - hence, the issue.


Alternatively, you can use with_object

replacements.each.with_object(text) do |(k,v), text|
    text.gsub!(k,v)
end

4 Comments

with_object has an opposite parameters order: |(k, v), text|.
@mudasobwa Thanks, will fix it
You don't need the conditioning. That is some meaningless thing that the OP put.
@sawa Arigatou gozaimasu !! Did some updates based on your feedback.

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.