2011-09-22 2 views
1

반복 블록에서 반복 객체를 호출하려면 어떻게해야합니까?반복자에서 iterating 객체 호출

# "self" is an Object, and not an iterating object I need. 
MyClass.some.method.chain.inject{|mean, i| (mean+=i)/self.size} 

는 내가이 작업을 수행해야 의미 :

@my_object = MyClass.some.method.chain 
@my_object.inject{|mean, i| (mean+=i)/@my_object.size} 
+0

를 선호하는 당신의 방법에 당신을 도울 몇 가지 예입니다 당신이 당신의 자신의 질문에 대답했다 생각합니다. 그것은 그것을하는 방법입니다. – rdvdijk

+0

나는 http://stackoverflow.com/questions/4341161/is-there-a-ruby-method-that-just-returns-the-value-of-a-block이 대답 할 것이라고 생각했으나 그렇지 않다. –

+1

아 - http://stackoverflow.com/questions/7284637/how-to-get-a-reference-to-a-dynamic-object-call 꽤 똑같은 일을하고 있습니다. 제가 방금 언급 한 질문을 통해 그것을 발견했습니다. –

답변

1

이 대답은 가장 가까운 것은 자기 루비에는이있다 없다 제임스 Kyburz의 answer to a similar question

의 복사본입니다.

여기

#example 1 not self needed numbers is the array 

numbers = [1, 2, 3] 

numbers.reduce(:+).to_f/numbers.size 

# example 2 using tap which gives access to self and returns self 
# hence why total variable is needed 

total = 0 
[1, 2, 3].tap {|a| total = a.reduce(:+).to_f/a.size } 

# instance_eval hack which accesses self, and the block after do is an expression 
# can return the average without an extra variable 

[1, 2, 3].instance_eval { self.reduce(:+).to_f/self.size } # => 2.0 

지금까지 내가 예 1

관련 문제