2014-10-18 61 views
0

我希望重复一个字的可选次数。但是,当我运行我的程序时,它似乎没有超过input[1].times do lineRuby .join方法返回原始数组的长度而不是连接字符串的长度

CODE:

def repeat(*input) 
    sentence = [] 
    if input.length == 1 
     "#{input[0]} #{input[0]}" 
    else 
     input[1].times do 
      sentence.push(input[0]) 
      sentence.join(" ") 
     end 
    end 
end 

puts repeat("Hey!") 

puts repeat("Hey", 3) 

OUTPUT:

Hey! Hey! 
3 

回答

0

您需要返回的句子,你想加入这句话的时间循环之外。

def repeat(*input) 
    sentence = [] 
    if input.length == 1 
     "#{input[0]} #{input[0]}" 
    else 
     input[1].times do 
      sentence.push(input[0]) 
     end 
     sentence = sentence.join(" ") 
     return sentence 
    end 
end 
+0

啊!是的,非常感谢你,即使只是将“.join”方法从'.times'循环中移出来也行,因为它应该返回最后一行。再次感谢! – scabbyjoe 2014-10-18 21:03:48

0

这里是这样做的一个小更紧凑的方式:

def say_hey(word, repeat=1) 
    puts ([word]*repeat).join(' ') 
end 

say_hey("Hey!") 
    #=> Hey! 
say_hey("Hey!", 14) 
    #=> Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! Hey! 
+0

因此,如果没有提供第二个参数,那么向第二个参数添加一个值会创建一个默认值? – scabbyjoe 2014-10-18 22:32:07

+0

这是正确的。还要注意该方法的第一种形式[Array#*](http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-2A)。 – 2014-10-18 22:43:17