ebarryc
ebarryc

Reputation: 1

I don't understand what's wrong with this simple Ruby code

I wrote this program to ask users for their age, and then tell them how old they will be in 10-50 years. I don't understand what's wrong with it :( I'm just a beginner and any help would be greatly appreciated.

print "How old are you?"

age = gets.chomp
i = 1

while i < 6
multiple = i * 10 + age
puts "In #{multiple} years you will be #{multiple}"
i++
end

Upvotes: 0

Views: 65

Answers (1)

sam-the-milkman
sam-the-milkman

Reputation: 41

Many ways to accomplish what you're trying to do. Make sure you're indenting blocks correctly - it'll make your code much more readable. Note that to_i converts your input from a String to an Integer. Also, try to name your variables more specifically; multiple doesn't really mean anything in your example.

puts "How old are you?"

age = gets.chomp.to_i

(1..5).each do |i|
  years_passed = i * 10
  new_age = years_passed + age
  puts "In #{years_passed} years you will be #{new_age}"
end

If you want to use a while loop, you could do:

puts "How old are you?"

age = gets.chomp.to_i
multiplier = 1

while multiplier <= 5
  years_passed = multiplier * 10
  new_age = years_passed + age
  puts "In #{years_passed} years you will be #{new_age}"
  multiplier += 1
end

Upvotes: 1

Related Questions