1

What's a good way to find sum of any two elements in a given array?

I have the following code, but it looks kind of ugly

def sum_to_n?(a, n)
  sums = []
  a.each_index do |i|
    b = a.drop(i+1)
    b.each_index do |j|
      sums << a[i] + b[j]
    end
  end
end
1
  • 2
    a method with method? name should return a boolean, it's a convention. Commented Oct 21, 2013 at 6:19

1 Answer 1

1
xs = [1, 5, 8, 10]
xs.combination(2).map { |x, y| x + y }
#=> [6, 9, 11, 13, 15, 18]
Sign up to request clarification or add additional context in comments.

6 Comments

Magical! Thanks for quick response. ;)
Or, for the general case xs.combination(n).map {|v| v.reduce(&:+) }
@p11y: yup, only note that vs.reduce(:+)
@tokland nice! Since when is this possible?
I think it's possible from 1.8.7, it's well documented. There is a reason why inject allows it: a catamorphism (folding) is usually a binary operation of two values (the accumulated and the element being processed) so it makes sense to get this operator (method). Anyway, I'd also like to have [1,2,3].map(:to_s) :)
|

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.