Ruby gets/puts only for strings?

前端 未结 4 1914
难免孤独
难免孤独 2020-12-09 10:07

I\'m new to Ruby and am currently working on some practice code which looks like the following:

puts \'Hello there, Can you tell me your favourite number?\'
         


        
4条回答
  •  星月不相逢
    2020-12-09 10:41

    you can also make sure the number that the user is using is an integer this way:

    num = Integer(gets.chomp)
    

    but you have to create a way to catch the error in case the user input otherwise like a char, or string so; it is must better to use:

    num = gets.chomp.to_i
    

    In case the user put another type of data, num will be equal to 0 like you can see in this test example:

    puts "give me a number:"
    num = gets.chomp.to_i
    if num >3
     puts "#{num} es mayor a 3 "
    else 
     puts "#{num} es menor a 3 o 3"
    end
    

    This a example of the interaction with that script:

    give me a number:
     sggd
    0 es menor a 3 o 3
    nil
    

    I hope this clarify better your point.

提交回复
热议问题