数组,按字母顺序排列,所有瓶盖之间交替 [英] Array that alphabetizes and alternates between all caps

查看:109
本文介绍了数组,按字母顺序排列,所有瓶盖之间交替的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让用户输入五个字,我相信我有。然后该程序需要吐按字母顺序排列的话,在全部大写其他单词是,第一个字开始,剩下的词语全部小写之中。

我最终将有循环切换至500字,而且只有在我需要改变循环的次数。我如何得到这个工作?

下面是我到目前为止有:

 字= []5.times做
  提出请输入一个单词
  单词LT;< gets.chomp
结束把words.sort.odd.upcase


解决方案

下面两种方法不使用索引。

  ARR =%W |敏捷的棕色狗跳过了懒惰的狐狸|
  #=> [了,快,棕色,狗,跳楼,过,了,懒惰,狐狸精]

请注意:

  arr.sort
  #=> [棕色,狗,狐狸精,跳楼,懒惰,过,快速,中,中]

1

  E = [:UC,:LC] .cycle
arr.sort.map {| W | (e.next ==:UC)? w.upcase:w.downcase}
  #=> [棕色,狗,狐狸精,跳楼,懒惰,过,快,中,重]

2

  arr.sort.each_sli​​ce(2).flat_map {| U,V | V' [u.upcase,v.downcase]:[u.upcase]}
  #=> [棕色,狗,狐狸精,跳楼,懒惰,过,快,中,重]

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

解决方案

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

这篇关于数组,按字母顺序排列,所有瓶盖之间交替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆