나는 Learn Ruby the Hard Way의 에 있습니다.Ruby에서 루프를 사용하고 함수로 변환하기
추가 신용 운동 1 묻습니다 :
Convert this while loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.
코드 :
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
당신은 내가 만들려고 노력으로 지금까지있어 볼 수 있듯이 블록을 함수로 만들지 만 변수를 변수로 만들지는 않습니다.
오류 : 내가 잘못
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
을 말할 때 이제 숫자 변수가 ...
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
난 그냥도 변수로 6을 대체 인수 함수를 내놓았다했다, 내가 가진 OP 편집 코드. 그러나, 당신이 말했듯이, 지금은 '숫자'가 시야에 없습니다 ... – Stn