在大写和小写之间交替

时间:2016-02-16 21:24:07

标签: arrays ruby

我试图让用户五次输入一个单词,然后在不使用each_with_index方法的情况下,用大写和小写交替拼写每行的答案。我也试图按字母顺序对答案进行排序。以下是我的所作所为:

words = []

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

 words.each do |word|
   if words.even?
     puts words.downcase
   elsif words.odd?
     puts words.upcase
   end
 end

但我尝试的一切都失败了。如何在没有each_with_index方法的情况下让用户输入在大写和小写之间交替?

4 个答案:

答案 0 :(得分:2)

words = %w| how now brown cow |

enum = [:upcase, :downcase].cycle
words.map { |w| w.send enum.next }
  #=> ["HOW", "now", " BROWN", "cow"]

答案 1 :(得分:1)

words.each_slice(2) {|f,s| puts f.downcase; puts s.upcase if s }

答案 2 :(得分:0)

试试这个

words = []
sorted_words = []

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

words.sort!.each do |w|
  if words.index(w).even?
    sorted_words << w.downcase
  else
    sorted_words << w.upcase
  end
end
p sorted_words

答案 3 :(得分:-1)

words = Array.new(5){puts "Please enter a word:"; gets.chomp}
words.inject(false){|up, word| puts word.send(up ? :upcase : :downcase); !up}