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

前端 未结 6 1107
一整个雨季
一整个雨季 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 06:45

    gets lets the user input a line and returns it as a value to your program. This value includes the trailing line break. If you then call chomp on that value, this line break is cut off. So no, what you have there is incorrect, it should rather be:

    1. gets gets a line of text, including a line break at the end.
      • This is the user input
    2. gets returns that line of text as a string value.
    3. Calling chomp on that value removes the line break

    The fact that you see the line of text on the screen is only because you entered it there in the first place. gets does not magically suppress output of things you entered.

提交回复
热议问题