我需要创建一个重复给定单词的方法,但我认为我的设计有问题。我需要在单词之间添加空格,我错过了什么?
def repeat(word, repeats=2)
sentence = word.to_s * repeats
return sentence
end
当然,你缺少了空格。
你可以这样做:
def repeat(word, repeats = 2)
Array.new(repeats, word).join(" ")
end
([word] * repeats).join(' ')
- Andrew Marshall([word] * repeats) * ' '
- pguardiariodef repeat(word, repeats=2)
([word] * repeats).join(" ")
end
repeat("Hello",4)
# => "Hello Hello Hello Hello"
def repeat(word,repeats=2) sentence = word.to_s * repeats return sentence.join(" ") end
,但在看到这个之后,我觉得那样做很愚蠢,也明白了为什么它是错的 :) - computer_smile这里有一个更接近你的方法,而且不使用临时数组:
def repeat(word, repeats=2)
("#{word} " * repeats).chop
end
"#{word} "
使用字符串插值将word转换为字符串并追加一个空格… * repeats
创建一个包含repeats个副本的字符串.chop
返回去掉最后一个字符(尾随空格)的字符串不需要创建数组可以使代码更快。
chomp!(" ")
和[0..-2]
都不够简洁或漂亮。 - Stefanw = 'kokot'
n = 13
n.times.map { w.each_char.to_a.shuffle.join }.tap { |a, _| a.capitalize! }.join(' ') << ?.