从迭代器调用迭代对象 [英] Call to iterating object from iterator

查看:177
本文介绍了从迭代器调用迭代对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何调用迭代块中的迭代对象?

How can I call for iterating object from iterating block?

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

我的意思是我需要这样做:

I mean I need to do this:

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


推荐答案

这个答案是James Kyburz的的副本回答类似的问题

This answer is a copy of James Kyburz's answer to a similar question


在ruby中没有这个,最接近的是self。

There is no this in ruby the nearest thing is self.

以下是一些帮助您上路的例子

Here are some examples to help you on your way



#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

So far I prefer example 1

这篇关于从迭代器调用迭代对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆