2009-12-16 5 views
2
class Setter 
    attr_accessor :foo 

    def initialize 
     @foo = "It aint easy being cheesy!" 
    end 

    def set 
     self.instance_eval { yield if block_given? } 
    end 
end 

options = Setter.new 

# Works 
options.instance_eval do 
    p foo 
end 

# Fails 
options.set do 
    p foo 
end 

왜 '설정'방법이 실패합니까?Ruby 인스턴스 평가

편집

그것을 알아 냈 ...

할 필요
def set 
    self.instance_eval { yield if block_given? } 
end 

:

def set(&blk) 
    instance_eval(&blk) 
end 

답변

2

네 - 수율이 정의 된 환경에서 평가한다.

>> foo = "wrong foo" 
>> options.set do 
?>  p foo 
>> end 
"wrong foo" 
:

좋은 쓰기 최대 here하지만, 간단한 예제 문제를 보여줍니다