简体   繁体   中英

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)

It's not necessary to print inside the function and also outside it - this will cause duplicate printing. Also you are calling print on the positive numbers but not calling print if they are negative or zero. Additionally, you are using print "#{n}" which is the same as print n .

As far as the title of your question goes - "keeps returning nil" - you can change your approach a bit to do the print calls outside the function.

def countdown(n)
  n <= 1 ? [n] : (n-1).downto(1).to_a
end
print countdown(n).join(", ")

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" 

Try this:

def countdown(n)   
  n.downto(n > 0 ? 0 : n) { |i| puts i }
end  

countdown(4)
# 4
# 3
# 2
# 1
# 0
countdown(-4)
# -4
countdown(0)
# 0

You didn't mention what is to be done if the argument is zero. I've assumed it's treated as a positive or negative number.

Admittedly, this is cheating, as it does not "Use a for loop, while loop, or unless loop...", but Ruby is designed mainly to use iterators and blocks. This, or something like it, is the way to go. I just had a thought: treat that as a suggestion, not a requirement.

By the way, among loops, Kernel#loop was not mentioned, which is strange, as it is quite useful. As for "for loops", who uses them? I never have, not even once.

If you must use a loop, you could do the following.

def countdown(n)
  while n > 0
    puts n
    n-= 1
  end
  puts n
end

countdown(4)
# 4
# 3
# 2
# 1
# 0
countdown(-4)
# -4    
countdown(0)
# 0

You may try this...

def sample (a)
 if a > 0
    (1..a).to_a.reverse
  else
    a
  end
end

Hope this will work for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM