2011-09-22 157 views
1

如何调用迭代块迭代对象?调用迭代器迭代对象

# "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