I need to get the user to input five words, which I believe I have. Then the program needs to spit the words in alphabetical order with every other word being in all-caps, s
I'd use:
user_input = %w(the quick red fox jumped)
uc_flag = true
output = []
user_input.sort.each { |w|
output << if uc_flag
w.upcase
else
w.downcase
end
uc_flag = !uc_flag
}
output # => ["FOX", "jumped", "QUICK", "red", "THE"]
It's old-school but is extremely fast as it only makes one pass through the array.
It can be written a bit more tersely using:
output << (uc_flag ? w.upcase : w.downcase)
but ternary statements are generally considered to be undesirable.
If the user is allowed to enter mixed-case words, use:
sort_by(&:downcase)
instead of sort
.
Just out of curiosity:
arr = %w(orange apple lemon melon lime)
a1, a2 = arr.sort.partition.with_index { |_, i| i.even? }
a1.map(&:downcase).zip(a2.map &:upcase).flatten.compact
with_index
can help you with the every other word problem:
words = %w(hello world this is test)
# => ["hello", "world", "this", "is", "test"]
words.map(&:downcase).sort.map.with_index {|word, index| index.odd? ? word : word.upcase}
# => ["HELLO", "is", "TEST", "this", "WORLD"]
Here are two ways that don't use indices.
arr = %w|the quicK brown dog jumpEd over the lazy fox|
#=> ["the", "quicK", "brown", "dog", "jumpEd", "over", "the", "lazy", "fox"]
Note:
arr.sort
#=> ["brown", "dog", "fox", "jumpEd", "lazy", "over", "quicK", "the", "the"]
#1
e = [:UC, :LC].cycle
arr.sort.map { |w| (e.next == :UC) ? w.upcase : w.downcase }
# => ["BROWN", "dog", "FOX", "jumped", "LAZY", "over", "QUICK", "the", "THE"]
#2
arr.sort.each_slice(2).flat_map { |u,v| v ? [u.upcase, v.downcase] : [u.upcase] }
# => ["BROWN", "dog", "FOX", "jumped", "LAZY", "over", "QUICK", "the", "THE"]
If I understand well (but the question is not so clear) you want to sort and then put one word out of two in uppercase and the other in lowercase:
words.sort.each_with_index.map{|w,i| i.odd? ? w.upcase : w.downcase }
Test:
words=%w( orange banana apple melon)
Result:
["APPLE", "banana", "MELON", "orange"]