我需要让用户输入五个单词,我相信我有。然后程序需要按字母顺序吐出单词,其他每个单词都是全部大写,从第一个单词开始,剩下的单词全部用小写。
我最终将循环切换到500个单词,而且它只是循环中我需要更改的数字。我如何让它工作?
这是我到目前为止所拥有的:
words = []
5.times do
puts "Please enter a word"
words << gets.chomp
end
puts words.sort.odd.upcase
答案 0 :(得分:1)
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"]
答案 1 :(得分:1)
以下两种不使用索引的方式。
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"]
答案 2 :(得分:0)
我会用:
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"]
这是老式的,但速度非常快,因为它只能通过阵列。
使用以下内容可以更简洁地写出来:
output << (uc_flag ? w.upcase : w.downcase)
但通常认为三元陈述是不受欢迎的。
如果允许用户输入大小写混合的单词,请使用:
sort_by(&:downcase)
而不是sort
。