2017-10-04 55 views
0

为了通过rspec测试,我需要得到一个简单的字符串以返回“num”次数。我一直在使用谷歌搜索,看起来时间方法应该有所帮助。从理论上我可以看到:Ruby.times方法返回变量而不是输出

num = 2 
string = "hello" 

num.times do 
    string 
end 

...应该工作吗?但输出继续返回为“2”,或任何“num”相等。我可以将它“放入'hello'”两次,但打印“hellohello”后仍然返回“2”。

也试过

num.times { string } 

我失去了对.times方法一些基本的东西,在这里?或者我应该以另一种方式进行讨论?

+3

的'times'方法重复调用的代码'num'次块 - 它不是“时代”(乘)运算符。为此使用'*'例如'“你好”* 2#=>“hellohello”' – mikej

回答

3

times将重复执行块:string将被解释两次,但该值不会用于任何事情。 num.times将返回num。您可以检查它在Ruby控制台:

> 2.times{ puts "hello" } 
hello 
hello 
=> 2 

你并不需要一个循环,你需要连接:

string = "hello" 
string + string 
# "hellohello" 
string + string + string 
# "hellohellohello" 

或者仅仅是想与数字,可以用乘法来避免多次加入:

string * 3 
# "hellohellohello" 
num = 2 
string * num 
# "hellohello" 

如果您需要2个string元素的列表,你可以使用:

[string] * num 
# ["hello", "hello"] 

Array.new(num) { string } 
# ["hello", "hello"] 

如果你想在中间的空间加入字符串:

Array.new(num, string).join(' ') 
# "hello hello" 

只是为了好玩,你也可以使用:

[string] * num * " " 

但它可能不太可读。

0

这是您要查找的行为吗?

def repeat(count, text) 
    text * count 
end 

repeat(2, "hello") # => "hellohello" 

(并没有采取任何措施来抵御有害输入)

+0

基本上,是的。我认为这里有很多答案表明使用像.times这样的循环可能是一个过度复杂的过程。 – oheydrew

相关问题