如何在Ruby中重复一次或多次String

时间:2017-05-24 17:00:13

标签: ruby

如何在Ruby中重复一次或多次String?

def repeat(*args)
  str, second_arg, count = "", args[1], 1
   if args[1] == nil
     args[1] = 1
   end
    while second_arg >= count
      str += args[0] + " "
      second_arg -= 1
    end

  return str
end

我概述的测试是:

describe "repeat" do
    it "should repeat" do
      expect(repeat("hello")).to eq("hello hello")
    end

    # Wait a second! How can you make the "repeat" method
    # take one *or* two arguments?
    #
    # Hint: *default values*
    it "should repeat a number of times" do
      expect(repeat("hello", 3)).to eq("hello hello hello")
    end
  end

如果缺少argument[1],我想用值“1”填充它,这样它至少会返回1.

这是我的错误:

Failures:

  1) Simon says repeat should repeat
     Failure/Error: expect(repeat("hello")).to eq("hello hello")
     NoMethodError:
       undefined method `>=' for nil:NilClass
     # ./lib/03_simon_says.rb:14:in `repeat'
     # ./spec/03_simon_says_spec.rb:39:in `block (3 levels) in <top (required)>'

4 个答案:

答案 0 :(得分:3)

此处if args[1] == nil您要验证ARGV中的第二个值是nil并将其设置为1,然后在while语句中您使用的second_arg已经使用args[1]的值,因此,很可能它不会通过您的验证:

if args[1] == nil
  args[1] = 1
end

您可以尝试在该验证中设置second_arg变量,而不是设置args[1]

if args[1] == nil
  second_arg = 1
end

此外,“ Ruby中的任何语句都会返回上次评估的表达式的值”,因此您只需将str作为repeat方法中的最后一个值即可将被评估为返回值。

答案 1 :(得分:1)

在设置args[1]之前,您必须设置second_arg

def repeat(*args)
    args[1] = 1 if args[1] == nil
    str, second_arg, count = "", args[1], 1

    while second_arg >= count
      str += args[0] + " "
      second_arg -= 1
    end

    return str
end

您也可以使用条件赋值运算符:

# The two lines do the same thing
args[1] = 1 if args[1] == nil
args[1] ||= 1

答案 2 :(得分:1)

你完全过于复杂了。这里绝对没有理由使用可变长度参数列表。它更慢,代码更多,而且不太清楚。测试代码自己说:“提示:*默认值*”

def repeat(str, count = 2)
    return Array.new(count, str).join(" ")
end

或者如果您更喜欢手动循环它:

def repeat(str, count = 2)
    result = str

    for _ in 0...count-1
        result += " " + str
    end

    return result
end

答案 3 :(得分:0)

"hello" * 5 # => "hellohellohellohellohello"

Array.new(5, "hello").join(" ") # => "hello hello hello hello hello"