1

I have a string:

a = 'bla \n bla \n bla \n'

And an array:

b = ['1', '2', '3']

I want to search through the string, and replace every nth instance of \n with the (n-1)th element from the array, resulting in:

a = 'bla 1 bla 2 bla 3'

What is the simplest way for me to do this?

2
  • Are you trying every permutation of every possible question with the same structure but different objects? Commented Dec 6, 2016 at 14:53
  • While the topic was similar the given responses are completely different. Some people replying took the time to give answers, one of which has helped me greatly. Commented Dec 6, 2016 at 14:57

3 Answers 3

5

String#gsub with a block makes short work of this:

a.gsub('\n') { b.shift }

Note that Array#shift modifies the original array. Make a copy of it first (b.dup) if that's a problem.

Sign up to request clarification or add additional context in comments.

1 Comment

I thinking about it, nice!)
1

You can use method sub

a = 'bla \n bla \n bla \n'
b = ['1', '2', '3']
b.each { |i| a.sub!('\n', i) }
#> a
#=> "bla 1 bla 2 bla 3" 

Comments

1

Just one more way using String#split and Array#zip

a.split('\n').zip(b).join
#=> "bla 1 bla 2 bla 3"

1 Comment

It looks like the best answer to me. Short, to the point and non-destructive. Sorry, I'm all out of votes.

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.