Search code examples
ruby-on-railsrubymethodsrubygemsclass-method

Ruby Loop Countdown Method keeps returning "nil"


I am working on a Ruby challenge for work, and I am unable to create a working method. Every method I try keeps returning "nil".

Here is the question:

Create a method that passes an integer argument to a single parameter. If the integer is greater than 0 print the numbers from the integer to 0. If the number is less than 0 simply print the integer. Use a for loop, while loop, or unless loop to print the range of numbers from the integer to 0.

For example:

sample(4)    
output = 3, 2, 1 

sample(-1)    
output  = -1    

Here is the code I tried to use

def countdown(n)   
    loop do  
    n -= 1  
    print "#{n}"  
    break if n <= 0   
end  
countdown(4)

Solution

  • A method returns the results of the last statement executed. Your loop is returning nil:

    def countdown(n)   
      x = loop do  
        n -= 1  
        puts "#{n}"  
        break if n <= 0   
      end
    
      x
    end  
    
    countdown(4)
    3
    2
    1
    0
    => nil 
    

    Now let's return something:

    def countdown(n)   
      loop do  
        puts "#{n}"  
        break if n <= 0   
        n -= 1  
      end
    
      "okay we're done"
    end  
    
    countdown(4)
    4
    3
    2
    1
    0
    => "okay we're done"