【问题标题】:Ruby .times method returns variable instead of outputRuby .times 方法返回变量而不是输出
【发布时间】:2018-03-15 12:08:05
【问题描述】:

为了通过 rspec 测试,我需要获取一个简单的字符串以返回“num”次。我一直在谷歌搜索,似乎 .times 方法应该有所帮助。从理论上我可以看到:

num = 2
string = "hello"

num.times do
  string
end

...应该有效吗?但输出继续返回为“2”,或任何“num”等于。我可以让它“放置'hello'”两次,但在打印“hellohello”后它仍然返回“2”。

也试过了

num.times { string }

我在这里错过了 .times 方法的一些基本内容吗?还是我应该用另一种方式来解决这个问题?

【问题讨论】:

  • times 方法重复调用代码块num 次 - 它不是“次”(乘法)运算符。为此使用*,例如"hello" * 2 # => "hellohello"

标签: ruby methods rspec iteration


【解决方案1】:

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 * " "

但它可能不太可读。

【讨论】:

    【解决方案2】:

    这是您要寻找的行为吗?

    def repeat(count, text)
      text * count
    end
    
    repeat(2, "hello") #  => "hellohello"
    

    (未采取任何措施来防范错误输入)

    【讨论】:

    • 基本上,是的。我认为这里的许多答案都表明使用像 .times 这样的循环可能过于复杂。
    猜你喜欢
    • 2018-02-25
    • 2021-04-10
    • 2020-02-08
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    相关资源
    最近更新 更多