开发者

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 = O开发者_开发技巧bject.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.


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.


list = []
until (word = gets.chomp) == "END"  do
  list << word
end

puts "Sorted Values:"
puts list.sort

This will take input until you give it "END" (you can change this as you wish).

I am calling Array#sort

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜