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

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • 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   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • 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}
Was This Post Helpful? 0
  • +
  • -

#3 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • 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(:+)
Was This Post Helpful? 0
  • +
  • -

#4 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


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

Re: Sum of Integers

Posted 15 November 2013 - 02:46 PM

More correctly (l..h).reduce(:+)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1