给定动态变量列表如何构建数组?

时间:2017-01-12 16:46:40

标签: ruby-on-rails ruby ruby-on-rails-4

考虑到很长的颜色列表,现在让我们说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"

由于

2 个答案:

答案 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"]