Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从迭代器调用迭代对象_Ruby_Iterator_Inject - Fatal编程技术网

Ruby 从迭代器调用迭代对象

Ruby 从迭代器调用迭代对象,ruby,iterator,inject,Ruby,Iterator,Inject,如何从迭代块调用迭代对象 # "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} 这是詹姆斯

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

# "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中没有这一点,最接近的东西是self

这里有一些例子可以帮助你在路上

到目前为止,我更喜欢示例1


这是詹姆斯·凯伯兹的答案

ruby中没有这一点,最接近的东西是self

这里有一些例子可以帮助你在路上

到目前为止,我更喜欢示例1


我想你已经回答了你自己的问题。这就是解决问题的方法。我本以为你会回答这个问题,但事实并非如此。啊,你做的事情和你做的差不多。通过我刚才提到的问题找到的。安德鲁,看起来就是这样!但它是黑客:)你应该把它作为一个答案贴到接受我想你已经回答了你自己的问题。这就是解决问题的方法。我本以为你会回答这个问题,但事实并非如此。啊,你做的事情和你做的差不多。通过我刚才提到的问题找到的。安德鲁,看起来就是这样!但它是黑客:)你应该把它作为一个答案来接受
#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