Reputation: 19
This is the code i am using, its purpose is for the user to enter an integer, the program will then take the sum of all the numbers up to and including the one entered. There is probable an easier way to do this
sum = 0
puts "please enter a number"
counter = gets.chomp.to_i
begin
sum += counter
counter -= 1
end while counter == 0
Upvotes: 1
Views: 3489
Reputation: 113
As I understand you are trying to sum elements of range. Giving number 3, you want to get sum which is 6.
One way (time consuming) is to use inject
or sum
. You can try following:
1. [*1..value].sum
2. [*1..value].inject(:+)
The other (recommended), very efficient way is to use this equation:
(value + 1) * (value) / 2
Upvotes: 0
Reputation: 44601
The issue with your code is in counter == 0
condition in your loop, since it runs only once and then if count
is not equal to 0
(in other words, if user's input wasn't 1
), it stops. You not only can make this without using loops, you can shorten the whole process:
counter = gets.to_i
sum = (0..counter).inject(:+)
P.S. As you could have noticed, you can omit .chomp
when you are using .to_i
.
Upvotes: 1
Reputation: 126
If I understood you correctly, you could try something like this...
puts "Please enter a positive number..."
number = gets.chomp.to_i
puts "Sum of all numbers is: #{ (1..number).inject { |sum, n| sum + n} }"
I'm using enumerable method 'inject' to sum up the total. Learn more about 'inject' method at http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-inject.
Hope this helps!
Upvotes: 0
Reputation: 189
Yes, use something like this (sum
from ActiveSupport):
sum = (counter + 1).times.sum
or without ActiveSupport:
sum = (counter + 1).times.inject(&:+)
Upvotes: 0