-7

我正在尝试为“墙上的 99 瓶啤酒”这首歌写一个 Ruby 循环,用于“学习编程”一书中的练习。我究竟做错了什么?我有以下内容:

    def bottles_of_beer 

      i = 99

      while i < 99 and i > 0 

        puts "#{a} bottles of beer on the wall. #{a} bottle of beer."

      i = i - 1

        puts "Take one down, pass it around. #{i} bottle of beer on the wall."

      end

    end
4

5 回答 5

3

您在第一个字符串中引用未定义的变量a

于 2013-08-27T17:35:53.700 回答
2

我已经将您的代码简化了很多:

i = 99
while i < 99 and (anything else)
  (anything)
end

试试看你现在能不能弄明白。

于 2013-08-27T17:36:57.117 回答
1

TL;博士

你的代码有很多问题,尤其是i开始等于 99,所以代码块的其余部分永远不会被评估。即使你解决了这个问题,a也将永远为零,因为你从来没有给它分配任何东西。

修复你的条件

有很多方法可以做到这一点,但您可能希望使用>=<=方法进行比较。

更加地道

使用Integer#downto和块会更惯用。例如:

12.downto(1) { |count| p "#{count} bottles of beer on the wall..." }
p "You drank the whole case!"
于 2013-08-27T18:41:57.870 回答
0

为了给你一个明确的答案,你的代码没有输出的原因有三个

  • 您设置i为 99 然后 loop while i < 99 and i > 0,因此永远不会执行循环。既然你总是在递减 i,没有什么比while i > 0

  • 您将变量a插入到您正在打印的字符串中。由于您尚未声明它,您的程序将拒绝运行,说undefined local variable or method 'a'

  • 你从来没有真正调用你的方法。

解决这三个问题给出了这个(非惯用但有效的)程序

def bottles_of_beer
  i = 99
  while i > 0
    puts "#{i} bottles of beer on the wall. #{i} bottle of beer."
    i = i - 1
    puts "Take one down, pass it around. #{i} bottle of beer on the wall."
  end
end

bottles_of_beer
于 2013-08-28T00:14:53.963 回答
0

也许...

99.downto(1) do |i|
  puts "#{i} bottle#{i==1 ? '' : 's'} of beer on the wall, #{i} bottle#{i==1 ? '' : 's'} of beer!"
  puts "Take one down, pass it around, #{i-1} bottle#{i-1==1 ? '' : 's'} of beer on the wall!"
end
于 2013-08-27T18:08:39.813 回答