2

我正在学习 Ruby the Hard Way 的第 33 章。

额外学分练习 1 询问:

将此 while 循环转换为可以调用的函数,并将测试中的 6 (i < 6) 替换为变量。

编码:

i = 0
numbers = []

while i < 6
  puts "At the top i is #{i}"
  numbers.push(i)

  i = i + 1
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end

puts "The numbers: "

for num in numbers
  puts num
end

我的尝试:

i = 0
numbers = []

def loops
while i < 6
  puts "At the top i is #{i}"
  numbers.push(i)

  i = i + 1
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end
 end

 loops
 puts "The numbers: "

for num in numbers
  puts num
end

正如你所看到的,我试图将块变成一个函数,但还没有把 6 变成一个变量。

错误:

ex33.rb:5:in `loops': undefined local variable or method `i' for main:Object (Na
meError)
        from ex33.rb:15:in `<main>'
    from ex33.rb:15:in `<main>'

我究竟做错了什么?

编辑:好的,改进了一点。现在数字变量超出范围......

def loops (i, second_number)
numbers = []
while i < second_number
  puts "At the top i is #{i}"
    i = i + 1
  numbers.push(i)
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end
 end

loops(0,6)
puts "The numbers: "

for num in numbers
  puts num
end
4

3 回答 3

0

当您说def时,i超出范围。该方法无法“看到”它。改为使用@i(@ 为变量提供更大的“可见性”),或移动i=6方法内部,或弄清楚如何在方法中使用参数。

于 2012-03-22T21:46:43.167 回答
0

正如@steenslag 所说,i超出loops. 我不建议切换到使用@i,因为i仅由loops.

您的函数是一个实用程序,可用于生成数字数组。该函数用于i确定它有多远(但函数的调用者并不关心这一点,它只想要结果numbers)。该函数还需要返回numbers,所以也将它移到里面loops

def loops
  i = 0
  numbers = []

  while i < 6
    puts "At the top i is #{i}"
    numbers.push(i)

    i = i + 1
    puts "Numbers now: #{numbers}"
    puts "At the bottom i is #{i}"
  end
end

您现在必须考虑调用者loops不再能看到的事实numbers。祝你学习顺利。

于 2012-03-22T21:58:33.040 回答
0

我可能误读了“转换 while 循环”,但我的解决方案是:

def loop(x, y)

   i = 0
   numbers = []

   while i < y
      puts "At the top i is #{i}"
      numbers.push(i)

      i += 1
      puts "Numbers now: ", numbers
      puts "At the bottom i is #{i}"
   end

   puts "The numbers: "

# remember you can write this 2 other ways?
numbers.each {|num| puts num }

end

loop(1, 6)
于 2016-02-12T13:58:07.480 回答