maudulus
maudulus

Reputation: 11035

Using Instance Variable to do Calculation

So I want to use instance variables to do something like

@array.each {|x,y|x+y}

It doesn't seem to be working, and I'm wondering if that is the correct syntax to use with an instance variable, or should it be something like

@array.each |x, y| x+y

or

@array.each [|x,y| x+y]

Do I need to use yield for this?

Upvotes: 0

Views: 92

Answers (4)

lucke84
lucke84

Reputation: 4636

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(:+)

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36860

If you want to sum the elements (which seems to be your purpose).

@array.inject(:+)

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44685

You are looking for inject:

@array.inject(:+)

Upvotes: 0

Shoe
Shoe

Reputation: 76240

You should have only one variable within the block:

@array.each { |x| ... }

The method each will traverse the array one by one.

Upvotes: 0

Related Questions