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

前端 未结 6 1109
一整个雨季
一整个雨季 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:42

    • "gets" allows user input but a new line will be added after the string (string means text or a sequence of characters)

      "gets.chomp" allows user input as well just like "gets", but there is not going to be a new line that is added after the string.

    Proof that there are differences between them:

    Gets.chomp

    puts "Enter first text:"
    text1 = gets.chomp
    puts "Enter second text:"
    text2 = gets.chomp
    puts text1 + text2
    

    Gets:

    puts "Enter first text:"
    text1 = gets
    puts "Enter second text:"
    text2 = gets
    puts text1 + text2
    

    Copy paste the code I gave you, run and you will see and know that they are both different.

提交回复
热议问题