# Sum of Integers

Page 1 of 1

## 3 Replies - 1821 Views - Last Post: 15 November 2013 - 02:46 PM

### #1 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

# Sum of Integers

Posted 29 November 2009 - 03:10 PM

Description: Finds the sum of integers from the starting point to the end point
```def sum(s, e) #s = start, e = end
sum = 0
for i in s..e
sum += i
end
return sum
end

#Example usage
puts sum(0,10) #=>55
```

Is This A Good Question/Topic? 0

## Replies To: Sum of Integers

### #2 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

## Re: Sum of Integers

Posted 16 January 2010 - 10:58 AM

This one liner has the same effect: low.upto(high).inject(low) {|sum, x| sum += x}

### #3 Karel-Lodewijk

Reputation: 455
• Posts: 864
• Joined: 17-March 11

## Re: Sum of Integers

Posted 29 December 2011 - 05:23 PM

Even shorter in ruby 1.9 + using ranges: (low..high).inject(:+)

### #4 Lemur

• Pragmatism over Dogma

Reputation: 1453
• Posts: 3,633
• Joined: 28-November 09

## Re: Sum of Integers

Posted 15 November 2013 - 02:46 PM

More correctly (l..h).reduce(:+)