Search code examples
rubysortinggets

Using gets command to sort array alphabetically in Ruby


I am a Ruby noob and am simply trying to use the gets command to sort a array of words ("dog", "cat", "ape") should be entered individually by gets and become ("ape", "cat", "dog")

I have tried:

list = Object.new
list = []
word = STDIN.gets
list.push(word)
$/ = "END"
puts list

Any help would be great as this is to help my daughter sort her homework faster and learn to type.


Solution

  • You can also enter all the words at once if you want to:

    >> words = gets.chomp.split(/,\s*/).sort
    dog, cat,ape                             #=> ["ape", "cat", "dog"]
    

    If you want to read them individually:

    >> words = [] #=> []
    >> until (word = gets.chomp).empty? do
    ..     words << word
    ..   end
    cat
    ape
    dog
             #=> nil
    >> words.sort #=> ["ape", "cat", "dog"]
    

    That's just copy/paste from IRB, but easy enough to make into the program you want.