Array that alphabetizes and alternates between all caps

后端 未结 5 991
面向向阳花
面向向阳花 2020-12-22 10:44

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

5条回答
  •  攒了一身酷
    2020-12-22 11:10

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

提交回复
热议问题