1

I am trying to find sum of each array.

(1..9).to_a.combination(3).to_a.each{ |item| item.inject{:+}}

But my code gives the followings.

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 2, 7], [1, 2, 8], [1, 2, 9], 
[1, 3, 4], [1, 3, 5], [1, 3, 6], [1, 3, 7], [1, 3, 8], ...

What I am expecting is something like this.

[6, 7, 8, 9,...]

How can I find sum of each array?

1
  • if you are using rails then you can use sum method like (1..9).to_a.combination(3).map{|a| a.sum(0)} Commented Apr 18, 2014 at 13:24

3 Answers 3

10

You are very close, a little change on your code may help:

(1..9).to_a.combination(3).map { |a| a.inject(:+) }
Sign up to request clarification or add additional context in comments.

Comments

6
(1..9).to_a.combination(3).to_a.map { |item| item.inject(:+) }

Comments

0

I found another way with #reduce.

(1..9).to_a.combination(3).map { |item| item.reduce(:+) }

1 Comment

reduce is an alias for inject, but I prefer it in this case.

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.