0

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
Bodhidarma
  • 519
  • 1
  • 7
  • 25

2 Answers2

2

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?.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

Ruby 2.4 has a solution for this:

input = gets(chomp: true)
# "abc"
tokhi
  • 21,044
  • 23
  • 95
  • 105