1

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}
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • I think you have answered your own question. That is the way to do it. – rdvdijk Sep 22 '11 at 08:31
  • I thought http://stackoverflow.com/questions/4341161/is-there-a-ruby-method-that-just-returns-the-value-of-a-block would answer it, but it doesn't. – Andrew Grimm Sep 22 '11 at 08:57
  • 1
    Ah - http://stackoverflow.com/questions/7284637/how-to-get-a-reference-to-a-dynamic-object-call is doing pretty much the exact same thing you are. Found it through the question I was just mentioning. – Andrew Grimm Sep 22 '11 at 09:01
  • Andrew, looks like that's it! But it is hacky :) You should post it as an answer to accept – fl00r Sep 22 '11 at 09:05

1 Answers1

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

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338