从迭代器调用迭代对象

发布于 2024-12-06 02:07:30 字数 310 浏览 1 评论 0原文

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

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

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}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城花音 2024-12-13 02:07:30

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

Ruby 中没有 this,最接近的是 self。

以下是一些可以帮助您的示例

#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

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

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

So far I prefer example 1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文