Learn Ruby theHardWayの第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>'
私は何が間違っているのですか?
編集:さて、それを少し改善しました。現在、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