使用`while`倒计时

时间:2015-12-08 03:45:44

标签: ruby loops while-loop countdown

我想为数字倒计时编写代码,并希望使用"HAPPY NEW YEAR!"while一起庆祝。

def countdown(number)
  while number > 0
    puts "#{number} SECOND(S)!"
    number -= 1
  end
  puts "HAPPY NEW YEAR!"
end

我的代码不起作用。这段代码有什么问题?

UPD 以下测试失败(来自@mudasobwa的评论):

describe '#countdown' do
  let(:countdown_output) { 
    "10 SECOND(S)!\n9 SECOND(S)!\n8 SECOND(S)!\n7 SECOND(S)!\n6 SECOND(S)!\n5 SECOND(S)!\n4 SECOND(S)!\n3 SECOND(S)!\n2 SECOND(S)!\n1 SECOND(S)!\n" 
  } 
  it "outputs '<n> SECOND(S)!' string to STDOUT for each count" do
    expect { countdown(10) }.to output(countdown_output).to_stdout
  end
  it 'returns HAPPY NEW YEAR!' do
    expect(countdown(12)).to eq "HAPPY NEW YEAR!"
  end
end

1 个答案:

答案 0 :(得分:1)

问题在于:

expect(countdown(12)).to eq "HAPPY NEW YEAR!"

您的功能打印 HNY输出到标准输出,而不是返回

要解决此问题,countdown方法应返回值:

def countdown(number)
  while number > 0
    puts "#{number} SECOND(S)!"
    number -= 1
  end
  # puts "HAPPY NEW YEAR!"
  "HAPPY NEW YEAR!"
end