patternrubyMinor
Sorting an array in alphabetical order
Viewed 0 times
arraysortingalphabeticalorder
Problem
I'm looking to get some feedback on this program I wrote - ways I could make it simpler or best practices methods.
Chapter 7:
Let's write a program which asks us to type in as many words as we
want (one word per line, continuing until we just press Enter on an
empty line), and which then repeats the words back to us in
alphabetical order. OK?
...
Assignment: Write the program we talked about at the very beginning of
this chapter. Hint: There's a lovely array method which will give you
a sorted version of an array:
Here's the program I wrote:
Chapter 7:
Let's write a program which asks us to type in as many words as we
want (one word per line, continuing until we just press Enter on an
empty line), and which then repeats the words back to us in
alphabetical order. OK?
...
Assignment: Write the program we talked about at the very beginning of
this chapter. Hint: There's a lovely array method which will give you
a sorted version of an array:
sort. Use it!Here's the program I wrote:
puts "This program will take your words and sort them alphabetically"
puts ""
puts "Type in a word and press enter. When you are done, press enter on an empty line to launch program."
inputArray = []
while (inputWord = gets.chomp) != ""
inputArray.push inputWord
puts "Current List is: " + inputArray.join(', ')
end
print "Your list in alphabetical order is: " + inputArray.sort.join(', ') + "."Solution
Flambino has already pointed out the issues in your code, so I'll just show how to tackle the problem with a different approach. A declarative and functional code (as opposed to imperative) favours immutability and known abstractions over manual control flow and in-place updates. Uusing
lazy from Ruby 2 and String#present? from active_support (so we can write the more declarative code we can) it would look like this:require 'active_support/core_ext/string'
sorted_words = $stdin.lines.lazy.map(&:strip).take_while(&:present?).sort
puts("Your list in alphabetical order is: #{sorted_words.join(', ')}.")Code Snippets
require 'active_support/core_ext/string'
sorted_words = $stdin.lines.lazy.map(&:strip).take_while(&:present?).sort
puts("Your list in alphabetical order is: #{sorted_words.join(', ')}.")Context
StackExchange Code Review Q#49482, answer score: 5
Revisions (0)
No revisions yet.