如何得到一个“动态”对象调用的参考? [英] How to get a reference to a 'dynamic' object call?

查看:82
本文介绍了如何得到一个“动态”对象调用的参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我的问题不是很清楚,但我想要做的是以下内容:

Well, my question is not very clear, but what I want to do is the following:

average = [1, 2, 3].inject(0) { |sum, el| sum + el } / this.size

在code以上不会因为可笑调用的工作这个,但我想要做到的是让一个参照阵列到我打电话注入上。 (在这种情况下[1,2,3]),由于我的无知,在我的红宝石与这个做到了。但是,你能告诉我怎么做是正确的?
是否有可能在所有做没有一个变量引用?

The code above won't work because of the ridiculous call to this, But what I want to accomplish is to get a reference to the array to which I'm calling inject on. (in this case [1, 2, 3]), Given my ignorance in ruby I did it with this. But, Could you please tell me how to do it right? Is it possible at all to do it without a variable reference?

在此先感谢!

推荐答案

有没有这红宝石最近的是自我。

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

到目前为止,我preFER例如1

So far I prefer example 1

这篇关于如何得到一个“动态”对象调用的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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