1

Given a very long list of colors, for now let's say 3:

["red", "green", "blue"]

How can I iterate over a string and do the following, match XXXX and return a string for each color type

sentences = Array.new
master_sentence = "This is a XXXX ball"

sa.push("This is a XXXX ball")

Where sentences now contains:

"This is a red ball"
"This is a green ball"
"This is a blue ball"
2
  • 2
    What is a "dynamic list of variables"? And where is that dynamic list of variables in your code? Also, what does this have to do with ruby-on-rails or the weirdly specific ruby-on-rails4? Commented Jan 12, 2017 at 16:53
  • 1
    just go through docs you don't need to ask all these simple questions on stack overflow Commented Jan 12, 2017 at 16:59

2 Answers 2

2

You can iterate by using map:

array = ["red", "green", "blue"]
master_sentence = "This is a XXXX ball"

array.map {|color| master_sentence.gsub(/XXXX/, color)}
=> ["This is a red ball", 
    "This is a green ball", 
    "This is a blue ball"]
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this?

 a = ["red", "green", "blue"]
=> ["red", "green", "blue"]
 a.map{|x| "This is a #{x} ball"}
=> ["This is a red ball", "This is a green ball", "This is a blue ball"]

2 Comments

I appreciate this, the problem with this answer is the sentence needs to be handled dynamically as seen in the other answer.
I see, i misunderstood.

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.