jlstr
jlstr

Reputation: 3056

How to get a reference to a 'dynamic' object call?

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

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?

Thanks in advance!

Upvotes: 2

Views: 137

Answers (2)

James Kyburz
James Kyburz

Reputation: 14463

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

Upvotes: 4

John
John

Reputation: 2141

'this' doesn't refer to the array, so that won't work at all. I don't think it's possible to get a reference to the array as you have declared it. But you will never run into such a problem, because if the array is hardwired into the code like that, then the divisor might as well be too, so you can just write '/3' at the end.

In the general case where you have an array of unknown size, you would also have a name for the array, so you could use that. Like:

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

Upvotes: 0

Related Questions