Home > OS >  Problem with my program with ruby, i don't understand
Problem with my program with ruby, i don't understand

Time:09-17

puts "Quel âge tu as ?"

print ">"

age = gets.chomp.to_i
i = 0

    
while age > 0 

    

    puts "Il y a "   age.to_s   " ans"   " tu avais : "   i.to_s   " ans"
    age -= 1
    i  = 1 

    break if age = i
    puts "Il y a "   age.to_s   " ans"   " tu avais la moitié de ton âge !"
    age = i
end
    

I have a problem with my program on Ruby On Rails. I apologize in advance for my English.

I train on this language by doing an exercise that allows you to enter your age, and to see how old you are in a given year.

But for example. When we reach half our age, for example 20 years old I want to display (in french)

"Ten years ago, you were half your age!"

that I wanted to put thanks to the "break if", but that produces only one line of code. I hope you have understood otherwise do not hesitate to ask for clarification.

Thank you in advance.

CodePudding user response:

break does not necessarily need to be a one-line you can have break all by itself after a condition is met, also you have an issue in your code where you are comparing with an = instead of a ==


if (condition == true)
  break 
end

your code could look like

puts "Quel âge tu as ?"

print ">"

age = gets.chomp.to_i
i = 0

    
while age > 0 

    

    puts "Il y a "   age.to_s   " ans tu avais : "   i.to_s   " ans"
    age -= 1
    i  = 1 

    if age == i
        puts "Il y a "   age.to_s   " ans tu avais la moitié de ton âge !"
        break
    end
end

Note: may I also point that your code will not show "Ten years ago, you were half your age!" if the age entered is odd

CodePudding user response:

A break statement stops your while loop. You probably want an if expression:

while age > 0
  if age == i
    puts "Il y a #{age} ans tu avais la moitié de ton âge !"
  else
    puts "Il y a #{age} ans tu avais : #{i} ans"
  end
  age -= 1
  i  = 1
end

You can get rid of the manual incrementing / decrementing by using downto and with_index:

age.downto(1).with_index do |a, i|
  if a == i
    puts "Il y a #{a} ans tu avais la moitié de ton âge !"
  else
    puts "Il y a #{a} ans tu avais : #{i} ans"
  end
end
  • Related