Design problem with 'inject'

L

Louis J Scoras

This works fine
sum = 0
arr = (1..10).to_a
arr.inject(0) { |sum, i| sum += ( i == 3 ? 0 : i ) } => 52

The assignment to sum is useless. Only the return value matters to inject.

arr.inject(0) { |sum, i| sum + ( i == 3 ? 0 : i ) }

Does the same thing. Actually, its more correct. The above is only
doing what you want because an assignment returns the value it assigns
to:

sum += i
sum = sum + i
sum + i #evaluates to this after side-effect
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top