【发布时间】:2012-04-07 12:35:41
【问题描述】:
我在 Chapter 33 上 Learn Ruby the Hard Way。
额外学分练习 1 询问:
将此 while 循环转换为您可以调用的函数,并替换 6 在带有变量的测试(i
代码:
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>'
我做错了什么?
编辑:好的,改进了一点。现在 numbers 变量超出了范围...
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
【问题讨论】:
标签: ruby function loops while-loop learn-ruby-the-hard-way