In general terms, there's no difference between a local and a instance variable, except for its scope. You can use it the very same way.
The problem with your code is that there's no each with two variables (x
and y
, in your example) for arrays.
You can do either:
total = 0
@array.each { |x| total += x }
Or:
total = @array.inject(0) { |tot, x| tot += x }
Or:
total = @array.inject { |tot, x| tot += x }
Which can be written also like this:
total = @array.inject(:+)