2017-11-17 3 views
0

내가이 일을하고있어 작동 :Proc.new가 아니라 to_proc을 사용하여 instance_eval을 호출하는 중 오류가 발생하는 이유는 무엇입니까?

class B 
    def value 
    "X" 
    end 
end 

class A 
    def initialize(context) 
    @context = context 
    end 

    def m 
    Proc.new do 
     value 
    end 
    end 

    def execute 
    @context.instance_eval(&m) 
    end 
end 

A.new(B.new).execute #=> "X" 

그러나 m.to_proc를 호출

class B 
    def value 
    "X" 
    end 
end 

class A 
    def initialize(context) 
    @context = context 
    end 

    def m 
    value 
    end 

    def execute 
    @context.instance_eval(&m.to_proc) 
    end 
end 

A.new(B.new).execute #=> NameError: undefined local variable or method `value' for #<A:0x007fae2ab02040 @context=#<B:0x007fae2ab02108>> 

나는이 두 가지 예는 다른 이유를 알고 싶어 ... 작동하지 않는 방법을 만드는 방법 to_proc

답변

0

두 번째 코드에서을 호출 한 결과를 반환하는 m을 호출합니다., 이는 정의되지 않았습니다. (그리고 심지어 어떻게 든 마술 B#value를 호출 한 경우 경우, 다음 B#value 당신이 거기 NoMethodError을 얻을 것 있도록 StringString들, to_proc에 응답하지 않습니다 반환합니다.) 첫 조각에서, 당신은 Proc를 반환하는 m 전화 .

호출 결과 대신 m자체를으로 전달하려는 것 같습니다. Ruby에서 메서드는 객체가 아니므로 메서드를 객체로 가져 와서 전달할 수는 없습니다. 메서드가 객체 인 경우에도 m은 여전히 ​​참조가 아닌 m을 호출하는 구문입니다. to_proc에 대한 호출이 & 때문에, 여기에 완전히 중복이라고

@context.instance_eval(&method(:m).to_proc) 

참고 :이 방법을 나타내는 Method 객체를 반환 Object#method 방법을 사용하여, 첫번째 방법에 대한 반사 프록시 루비의 반사 API를 요청해야 인수가 Proc이 아닌 경우 to_proc을 호출합니다. (당신은 Symbol#to_proc를 호출하기 전에 foo.map(&:bar) 같은 무언가를 볼 수 있습니다.)

@context.instance_eval(&method(:m)) 
+0

미안 해요, 블록의 PROC로 변환하는 "&"전에'm.to_proc'를 놓친 여전히 작동하지 않습니다. – Leantraxxx

관련 문제