2015-08-26 56 views
0

我需要讓用戶輸入五個單詞,我相信我有這個單詞。然後,程序需要按照字母順序吐出單詞,其他單詞全部大寫,從第一個單詞開始,其餘單詞全部小寫。所有大寫字母排列並交替排列的數組

我最終會將循環切換到500個字,而且這只是我需要更改的循環中的數字。我如何得到這個工作?

這是我到目前爲止有:

words = [] 

5.times do 
    puts "Please enter a word" 
    words << gets.chomp 
end 

puts words.sort.odd.upcase 
+3

請給我們一個輸入'%w(橙子蘋果檸檬甜瓜酸橙)'的例子。很難理解「隔一個字」和「剩餘」的意思。 – mudasobwa

+0

輸入詞可以混合大小寫嗎?原因是,你的問題沒有很好的定義,並留下太多的空間來猜測需求。 –

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

如果我沒有理解好(但問題不是那麼清楚)你想排序,然後把兩個大寫字母中的一個字和另一個小寫字母:

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

測試:

words=%w(orange banana apple melon) 

結果:

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

謝謝你這是我正在尋找。 – Mahler7

+0

,回答這個問題的國旗將不勝感激! ;) – tomsoft

+0

沒有必要,或者特別希望要求選擇您的答案。儘可能回答問題,不要擔心問題。積分積累良好的答案。 –

0

只是出於好奇:

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 
+0

使用'flat_map'而不是'map ... flatten' –

+0

@theTinMan在我的解決方案中沒有'map.flatten'。或者,至少我沒有看到,如何對'flat_map'做同樣的處理。 – mudasobwa

+0

是的。我錯過了'map'在'zip'裏面。繼續。 –

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