2

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
4

3 に答える 3

0

と言うとdefi範囲外になります。メソッドはそれを「見る」ことができません。代わりに使用@iする (@ は変数の「可視性」を高める) かi=6、メソッド内で を移動するか、メソッドでパラメーターを使用する方法を理解します。

于 2012-03-22T21:46:43.167 に答える
0

@steenslag が言うように、i内の範囲外ですloops。は でのみ使用される@iため、使用に切り替えることはお勧めしません。iloops

あなたの関数は、数値の配列を生成するために使用できるユーティリティです。関数はi、それがどれだけ進んだかを把握するために使用します(ただし、関数の呼び出し元はこれを気にせず、結果のみが必要numbersです)。関数は return も必要な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 に答える