Ruby循环倒计时方法不断返回"nil"

Ruby Loop Countdown Method keeps returning "nil"

我正在应对 Ruby 工作挑战,但我无法创建工作方法。我尝试的每一种方法都会返回“nil”。

这里是问题:

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    

这是我尝试使用的代码

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

在函数内部和外部都没有必要 print - 这会导致重复打印。此外,您正在对正数调用 print,但如果它们为负数或零则不调用 print。此外,您使用的 print "#{n}"print n.

相同

就你的问题标题而言 - "keeps returning nil" - 你可以稍微改变你的方法来在函数外进行 print 调用。

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

你可以试试这个...

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

希望这对你有用

一个方法return是最后一条语句执行的结果。你的循环是 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 

现在让我们return做点什么:

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" 

试试这个:

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

你没有提到如果参数为零要做什么。我假设它被视为正数或负数。

诚然,这是作弊,因为它没有 "Use a for loop, while loop, or unless loop...",但 Ruby 主要是为了使用迭代器和块而设计的。这,或类似的东西,是要走的路。我只是有一个想法:将其视为建议,而不是要求。

顺便说一下,在循环中,没有提到Kernel#loop,这很奇怪,因为它很有用。至于"for loops",谁在用?我从来没有,一次都没有。

如果必须使用循环,可以执行以下操作。

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