我在第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发布于 2012-03-22 21:58:33
正如@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-22 21:46:43
当你说def时,i就超出了范围。这个方法不能“看到”它。代之以使用@i (@使变量具有更大的“可见性”),或将i=6移动到方法中,或研究如何使用方法参数。
发布于 2016-02-12 13:58:07
我可能误解了“转换时间循环”,但我的解决方案是:
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)https://stackoverflow.com/questions/9830928
复制相似问题