I am creating a program that accepts ten numbers from a user. Then, it displays the total of the ten numbers, their average, and the smallest and largest numbers. Finally, it is supposed to display the word ‘Jackpot!’ for every number entered that is of the same or greater value than 100, and ‘Tough Luck.’ for every number less than 100.
My code does not seem to be working and will not run in Ruby.
puts 'Please enter 10 numbers one at a time.'
num1=gets.chomp
num2=gets.chomp
num3=gets.chomp
num4=gets.chomp
num5=gets.chomp
num6=gets.chomp
num7=gets.chomp
num8=gets.chomp
num9=gets.chomp
num10=gets.chomp
value_list=[num1, num2, num3, num4, num5, num6, num7, num8, num9, num10]
subtotal=0
for x in 0..9
subtotal=subtotal+value_list[x]
puts 'Total: ' + subtotal
average=subtotal/10.to_f
average=sprintf("%.2f",average)
puts 'Average: ' + average
puts 'Smallest value: ' + sprintf("%.2f",value_list.min.to_s)
puts 'Largest value: ' + sprintf("%.2f",value_list.min.to_s)
if num1..num10 >=100
puts 'Jackpot!'
else
puts 'Tough Luck.'
sleep 120
A few things:
You need to
endyour blocks:for ... end,if ... else ... end, etc. This is the main reason it won’t run, i.e. the parser doesn’t recognize it as valid syntax.gets.chompreturns a string, but you are looking for integers. Trygets.chomp.to_ito force integer types.'Total: ' + subtotal: you would be adding an integer to a string, which is not allowed. Ruby string interpolation goes like this (double quotes required):"Total: #{subtotal}". This will transform thesubtotalvariable into a string and insert it into the other string on the fly.I’m not sure what you’re trying to do here:
if num1..num10 >= 100. Is this if any member of the range is greater than 100, or if the sum is greater than 100?There’s also a lot of optimization you can do here. One good opportunity is when you have a lot of repeated code, as in
num1 = gets.chomp.to_i; num2 = gets ... etc.Here’s a version of your program that (I think) does what you want it to. If you’re serious about learning Ruby, go look up the documentation for some of these methods (
<<,inject,.timesetc):Hope this helps.