0

Isn't t violation of codes?

x = gets.to_i if x > 5 puts "wrong" elsif x <= 5 puts "right" else puts "error" end it works just fine when i enter numbers, i expected t would give error when i enter a string, but t puts right...why, why?

20th Apr 2017, 11:14 AM
Kelvine De Danielo
Kelvine De Danielo - avatar
2 ответов
+ 1
different languages have different output methods, 'puts' in C++ signifies for 'Output of string', C++ Is basic language,Complex languages like python and Ruby has different output method, you need to follow that to output,
20th Apr 2017, 11:27 AM
Joel Roy
Joel Roy - avatar
0
The "to_i" method also accepts strings as input: https://apidock.com/ruby/String/to_i The link above explains what the method does when it finds a string: > If there is not a valid number at the start of str, 0 is returned. I changed your code a bit to show exactly what to_i is doing, as shown here: https://code.sololearn.com/cgtvo6lTuYqK If you input "A", then x becomes 0, which is <= 5, and therefore "right" according to your code.
15th Jul 2017, 7:40 PM
Felipe Rechia
Felipe Rechia - avatar