1
foo = [10,20,30,40,50,60]
foo_total = 0
foo.each do |f|
 print foo_total += f
end
print foo_total

The output of this code sample will be 10 30 60 100 150 210 210 but I'm actually looking for 10 20 30 40 50 60 210 I know that it can be achieved by using the following code

foo = [10,20,30,40,50,60]
foo_total = 0
foo.each do |f|
 print f
 foo_total += f
end
print foo_total

However, is there a more elegant approach that needs just one line in the foo.each block?

edit: It's not only about the output, but also about having the variable foo_total that contains the sum of all values in foo

2
  • I suppose you could use an abomination like print (foo_total += f) - f. Commented Feb 5, 2014 at 17:57
  • 1
    print f; foo_total +=f would be one line, but not one statement. Commented Feb 5, 2014 at 18:00

2 Answers 2

1

Do as below

(arup~>~)$ pry --simple-prompt
>> foo = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> foo.push(foo.inject(:+))
=> [10, 20, 30, 40, 50, 60, 210]
>> 
Sign up to request clarification or add additional context in comments.

4 Comments

Just to enhance, since OP seems to be looking for a string: foo.join(' ')
I doubt the OP wants a string. Using print will result in the values being output on a single line in the console, but nowhere is there an indication that the array should be joined or "stringified" in any way.
@theTinMan is right. I want to print each number in foo and also have the variable foo_total that contains the sum of all values in foo
My bad, sorry folks (I should not be commenting on SO on low sleep) :-)
1

How about:

foo.each do |f|
  foo_total += f.tap { |f1| print f1 }
end

1 Comment

+1 for anything with tap, though I doubt you'd use this just to save a line of code. (I love the sound of that method. tap.tap.tap is even better.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.