代码之家  ›  专栏  ›  技术社区  ›  oheydrew

红宝石times方法返回变量而不是输出

  •  0
  • oheydrew  · 技术社区  · 8 年前

    为了通过rspec测试,我需要得到一个简单的字符串,并多次返回“num”。我一直在谷歌上搜索,它似乎是。时间方法应该有帮助。从理论上讲,我可以看到:

    num = 2
    string = "hello"
    
    num.times do
      string
    end
    

    也尝试过

    num.times { string }
    

    我是否遗漏了一些基本的东西。时间方法,在这里?还是我应该换一种方式?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Eric Duminil    8 年前

    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] * num
    # ["hello", "hello"]
    

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

    如果要用中间的空格连接字符串:

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

    为了好玩,您还可以使用:

    [string] * num * " "
    

    但它可能不是真正可读的。

        2
  •  0
  •   Pend    8 年前

    这就是你想要的行为吗?

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

    推荐文章