Ruby gets/puts only for strings?

前端 未结 4 1884
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2020-12-09 10:41

    I wrote a similar program as yours. Here is how I finally got it to work properly! I had to assign the favorite number to be an integer. Then, in the next line I set the new_fav_num with the value of fav_num +1 and then converted it to string. After that, you can just plug your code into the return statement that you want to say to the user, only you have to convert the first fav_num to a string.

    puts "What is your favorite number?"
    
    fav_num = gets.chomp.to_i
    
    new_fav_num = (fav_num + 1).to_s
    
    puts "Your favorite number is " + fav_num.to_s + ". That's not bad, but " +
    new_fav_num + " is bigger and better!"

    Hope this helps.

    0 讨论(0)
  • 2020-12-09 10:43

    If you are using to_i, then chomp before that is redundant. So you can do:

    puts 'Hello there, Can you tell me your favourite number?'
    num = gets.to_i
    puts 'Your favourite number is ' + num.to_s + '?'
    puts 'Well its not bad but  ' + (num * 10).to_s + ' is literally 10 times better!'
    

    But generally, using "#{}" is better since you do not have to care about to_s, and it runs faster, and is easier to see. The method String#+ is particularly very slow.

    puts 'Hello there, Can you tell me your favourite number?'
    num = gets.to_i
    puts "Your favourite number is #{num}?"
    puts "Well its not bad but  #{num * 10} is literally 10 times better!"
    
    0 讨论(0)
  • 2020-12-09 10:47

    Use the to_i method to convert it to an integer. In other words, change this:

    num = gets.chomp
    

    To this:

    num = gets.chomp.to_i
    
    0 讨论(0)
提交回复
热议问题