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, starting with the first word, and the remaining words being in all lowercase.
I'm eventually going to have switch the loop to 500 words, and it's only the number in the loop that I need to change. How do I get this to work?
Here's what I have so far:
words = []
5.times do
puts "Please enter a word"
words << gets.chomp
end
puts words.sort.odd.upcase
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"]
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
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
.