Home > Net >  My ruby code is reliant on the number of the line appearing before the prompt. How do I fix this?
My ruby code is reliant on the number of the line appearing before the prompt. How do I fix this?

Time:10-14

def main()
count = 1
while count <= 10
puts "#{count}" " Enter integer 1: "
int1=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 2: "
int2=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 3: "
int3=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 4: "
int4=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 5: "
int5=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 6: "
int6=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 7: "
int7=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 8: "
int8=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 9: "
int9=gets.chomp.to_i

count = count   1

puts "#{count}" " Enter integer 10: "
int10=gets.chomp.to_i

count = count   1


sum=int1 int2 int3 int4 int5 int6 int7 int8 int9 int10

end
puts "Total is: #{sum}"
end

main()

I made a program on ruby that prompts the user to enter a number 10 times and sums all the inputted numbers together. The only problem is that my code is reliant on the number to the corresponding line appearing before the line. For example, the first prompt is "1 Enter integer 1:" while what I'm aiming to make it is "Enter integer 1:".

Another issue I have is that I don't know how to make the input appear on the same line as the prompt. It appears on a new line, for example "1 Enter integer 1: while I want it to be "1 Enter integer 1: 156" 1"

Thank you.

CodePudding user response:

The ruby REPL irb is line-at-a-time, so you can't get your input on the same line in the standard environment. (Other ways of doing it are of course available, up to and including a full Rails app! Which is far more than you want here, of course.)

To resolve your main issue, though, consider using an array to gather your input. You could then condense your code considerably, to something like this:

array = []
for i in 1..10 do
  puts "Enter integer #{i}:"
  array.push(gets.to_i)
end
sum = array.sum

If you don't need to prompt the user with a counter of the numbers they've entered, you could simplify even further like this:

array = []
10.times do
  puts "Enter integer:"
  array.push(gets.to_i)
end
sum = array.sum

CodePudding user response:

sum = 0
(1..10).each do |i|
  print "#{i} Enter integer: "
  sum  = gets.chomp.to_i
end
puts "Sum is "   sum.to_s

puts will add a newline to the output, print doesn't.

  • Related