[英]Given an array of strings varying in length, how can I replace every string with the same word
I have to replace a number of strings with the same word, lets say that word is "plum".我必须用同一个词替换一些字符串,假设这个词是“plum”。
An example could be... "This is a string" and expected output would be "plum plum plum plum" or "I'm happy" output "plum plum"一个例子可能是......“这是一个字符串”,预期输出将是“李子李子李子”或“我很高兴”输出“李子李子”
So far I have converted the string into an array, mapped and counted using...到目前为止,我已将字符串转换为数组,并使用...
string = sentence.split(&:map).to_a
n = string.count.to_i
I am now trying to replace each string in the array using sentence.gsub[0..n]
which I expected to replace each position in the array with my word.我现在正在尝试使用
sentence.gsub[0..n]
替换数组中的每个字符串,我希望用我的单词替换数组中的每个位置。
I'm sure this is not the best way to do this, however I would really appreciate help on this particular method to help my understanding of where I've gone wrong in my thinking as well as finding out that I could have done it with far cleaner code我敢肯定这不是最好的方法,但是我真的很感激这个特定方法的帮助,以帮助我理解我的想法哪里出错了,并发现我可以做到这一点更干净的代码
You can try this way:你可以试试这个方法:
"This is a string".split.map { "plum" }.join(" ")
=> "plum plum plum plum"
Or by using gsub
:或者通过使用
gsub
:
"This is a string".gsub(/[^\s]+/, "plum")
=> "plum plum plum plum"
You can just repeat "plum" as many times as you have words...您可以根据单词重复“梅花”多少次...
sentence = "This is a string"
("plum " * sentence.split.count).strip
=> "plum plum plum plum"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.