在所有大写字母之间按字母顺序排列和交替的数组

我需要让用户输入五个单词,我相信我有。 然后程序需要按字母顺序吐出单词,其他每个单词都在全部大写字母中,从第一个单词开始,剩下的单词全部为小写。

我最终将把循环切换到500个单词,并且它只是循环中需要更改的数字。 我如何让它工作?

这是我到目前为止所拥有的:

words = [] 5.times do puts "Please enter a word" words << gets.chomp end puts words.sort.odd.upcase 

with_index可以帮助您解决所有其他单词问题:

 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"] 

以下是两种不使用索引的方法。

 arr = %w|the quicK brown dog jumpEd over the lazy fox| #=> ["the", "quicK", "brown", "dog", "jumpEd", "over", "the", "lazy", "fox"] 

注意:

 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"] 

如果我理解得很好(但问题不是那么清楚)你想要排序,然后用两个大写字母和另一个小写字母:

 words.sort.each_with_index.map{|w,i| i.odd? ? w.upcase : w.downcase } 

测试:

 words=%w( orange banana apple melon) 

结果:

 ["APPLE", "banana", "MELON", "orange"] 

只是出于好奇:

 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 

我用的是:

 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"] 

这是老派,但速度非常快,因为它只能通过arrays。

可以使用以下方式更简洁地编写:

 output << (uc_flag ? w.upcase : w.downcase) 

但通常认为三元陈述是不可取的。

如果允许用户输入大小写混合的单词,请使用:

 sort_by(&:downcase) 

而不是sort