rubynewlinegetschomp

How to receive data from user without ruby adding an extra newline


I am trying to create a program that alphabetizes a users' word entries. However, inspection of the users entries reveals that ruby is for some reason adding a newline character to each word. For instance, If i enter Dog, Cat, Rabbit the program returns ["Cat\n", "Dog\n", "Rabbit\n"] How do i prevent this from happening?

 words = []
    puts "Enter a word: "
      until (word = gets).to_s.chomp.empty?
        puts "Enter a word: "
        words << word
      end

    puts words.sort.inspect

Solution

  • Change your code to:

    until (word = gets.chomp).empty?
    

    The way you're doing it now:

    (word = gets).to_s.chomp.empty?
    

    gets the string from the keyboard input, but it isn't returned to your code until the user presses Return, which adds the new-line, or carriage-return + new-line on Windows.

    to_s isn't necessary because you're already getting the value from the keyboard as a string.

    chomp needs to be tied to gets if you want all the input devoid of the trailing new-line or new-line/carriage-return. That will work fine when testing for empty?.