2011-11-12 5 views
0

저는 Procs, 블록, 람다로 뛰어 들고 있습니다. 나는 다른 일을 시도 주변 noodling하고있어,하지만 난이 작동하지 않는 이유에 대해 확실 해요 :Proc를 메소드에 전달하려는 시도가 잘못되었습니다.

def iterate(ary, &code) 
    ary.each_with_index do |n, i| 
    ary[i] = code.call(n) 
    end 
end 

iterator = Proc.new do |n| 
    n ** 2 
end 

p iterate([1,2,3], iterator) 

# `iterate': wrong number of arguments (2 for 1) (ArgumentError) 

답변

3

마지막 메서드의 매개 변수 앞에있는 & 기호는 block as parameter를 명시 적으로 정의하기위한 것입니다. 블록 대신 시저 매개 변수를 사용 1) : 귀하의 경우

당신은이 개 방법이

def iterate(ary, code) 
    ary.each_with_index do |n, i| 
    ary[i] = code.call(n) 
    end 
end 

iterator = Proc.new do |n| 
    n ** 2 
end 

p iterate([1,2,3], iterator) # => [1, 4, 9] 

또는 2) 대신 proc 디렉토리 생성의 블록을 사용

def iterate(ary, &code) 
    ary.each_with_index do |n, i| 
    ary[i] = code.call(n) 
    end 
end 

p iterate([1,2,3]) { |n| n ** 2 } # => [1, 4, 9] 
1

내가 생각하는 당신이 (오히려 블록보다) 발동에 전달하는, 당신 돈 메소드 정의의 code 매개 변수 앞에 &이 필요 없습니다.

관련 문제