【问题标题】:Call to iterating object from iterator从迭代器调用迭代对象
【发布时间】:2011-11-22 15:02:39
【问题描述】:

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

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

【问题讨论】:

标签: ruby iterator inject


【解决方案1】:

此答案是 James Kyburz 的 answer to a similar question 的副本

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 2017-12-18
    • 1970-01-01
    • 2016-03-08
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    相关资源
    最近更新 更多