Search code examples
rubyloopswhile-loopcountdown

Countdown using `while`


I want to write code for a number countdown and want to celebrate with "HAPPY NEW YEAR!" using while.

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

My code doesn't work. What's wrong with this code?

UPD Failing test is below (moved here from comments by @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

Solution

  • The problem is here:

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

    Your function is printing HNY out to stdout, not returning it.

    To fix the problem, countdown method should return the value instead:

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