Should repeat a number of times

后端 未结 3 1227
难免孤独
难免孤独 2021-01-16 16:44

Here is simon_says_spec.rb

require simon_says
     describe \"repeat\" do
        it \"should repeat\" do
          repeat(\"hello\").should == \"hello hello         


        
相关标签:
3条回答
  • 2021-01-16 17:23

    You are missing the end statement for your do loop.

    def repeat(x, y = 2)
        y.times do print x + ' ' end
    end
    
    0 讨论(0)
  • 2021-01-16 17:33

    Picking up where @Arup left off (you've edited the question with a follow-up)

    1. you are using a non-ASCII char instead of ' - ruby does not like that.
    2. Your code does not return the chained text, but rather the number of times you multiplied it (it does print the result though)

      3.times do '123' end
      # => 3
      

      So you test will fail.
      A better way to do that will be

      y.times.map { x + ' ' }.join
      

    And in a more ruby way:

    ([x] * y).join(' ')
    
    0 讨论(0)
  • 2021-01-16 17:43

    In the below part, you passed only 1 argument instead 2.

    describe "repeat" do
            it "should repeat" do
              repeat("hello").should == "hello hello"
              #        ^ why only 1 argument ?
            end
    

    As per your code, it should be repeat("hello", 2).should == "hello hello".

    As per commented hints, you can write also :-

    def repeat(x, y = 2)
       y.times { print x + ‘ ‘ }
    end
    

    Now, the test code you wrote, will work without error, with above modified method definition.

    require simon_says
    
    describe "repeat" do
      it "should repeat" do
        # here you are not passsing the second argument. But *repeat* method has `2`
        # as its default value of the second argument. So no issue will be here.
        repeat("hello").should == "hello hello"
      end
    
      it "should repeat a number of times" do
        repeat("hello", 3).should == "hello hello hello"
      end
    end
    

    Read this default argument to know, how default argument works in Ruby.

    0 讨论(0)
提交回复
热议问题