How to use “gets” and “gets.chomp” in Ruby

前端 未结 6 1112
一整个雨季
一整个雨季 2020-12-01 06:29

I learned that gets creates a new line and asks the user to input something, and gets.chomp does the same thing except that it does not create a ne

6条回答
  •  春和景丽
    2020-12-01 07:00

    The question shouldn't be "Is this the right order?" but more "is this is the right way of approaching this?"

    Consider this, which is more or less what you want to achieve:

    1. You assign a variable called tmp the return value of gets, which is a String.
    2. Then you call String's chomp method on that object and you can see that chomp removed the trailing new-line.

      Actually what chomp does, is remove the Enter character ("\n") at the end of your string. When you type h e l l o, one character at a time, and then press Enter gets takes all the letters and the Enter key's new-line character ("\n").

      1. tmp = gets
      hello
      =>"hello\n"
      
      2. tmp.chomp
      "hello"
      

    gets is your user's input. Also, it's good to know that *gets means "get string" and puts means "put string". That means these methods are dealing with Strings only.

提交回复
热议问题