考虑到很长的颜色列表,现在让我们说3:
["red", "green", "blue"]
如何迭代字符串并执行以下操作,匹配XXXX并为每种颜色类型返回一个字符串
sentences = Array.new
master_sentence = "This is a XXXX ball"
sa.push("This is a XXXX ball")
现在句子包含:
"This is a red ball"
"This is a green ball"
"This is a blue ball"
由于
答案 0 :(得分:2)
您可以使用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"]
答案 1 :(得分:1)
这样的东西?
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"]