2012-03-22 2 views
2

나는 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 

답변

0

@steenslag에 따르면 iloops 범위 밖에 있습니다. iloops에 의해서만 사용되기 때문에 @i을 사용하도록 전환하지 않는 것이 좋습니다.

함수는 숫자 배열을 생성하는 데 사용할 수있는 유틸리티입니다. 이 함수는 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를 볼 수 있다는 사실에 대해 생각해야합니다. 학습을 통해 행운을 빈다.

내가 오해했을 수
+0

난 그냥도 변수로 6을 대체 인수 함수를 내놓았다했다, 내가 가진 OP 편집 코드. 그러나, 당신이 말했듯이, 지금은 '숫자'가 시야에 없습니다 ... – Stn

0

범위를 벗어나, i이 범위를 벗어나. 이 방법은 그것을 "볼"수 없다. 대신 @i을 사용하십시오 (@는 변수에 더 큰 "가시성"을 제공합니다). 또는 메서드 내에서 i=6을 이동하거나 메서드에 매개 변수를 사용하는 방법을 파악하십시오.

0

이 'while 루프 변환'하지만 내 솔루션이었다

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)