如何在Ruby中使用upcase-downcase之前先排序?

时间:2016-01-08 10:24:18

标签: ruby

这段代码几乎是正确的,但我需要按字母顺序对输入进行排序,然后才能在upcase和downcase之间交替。

football_team = []
5.times do |i|
  puts "Please enter a UK football team:"
  team = gets.chomp
  if i.even?
    football_team << team.upcase
  else
    football_team << team.downcase
  end
end

puts football_team

我无法使用each_with_index

2 个答案:

答案 0 :(得分:3)

  

我需要按字母顺序对输入进行排序,然后才能在upcase和downcase之间交替。

我可以识别出3个部分:

  1. 收集输入
  2. 按字母排序
  3. upcase and downcase
  4. 显然,这不可能在一个循环中完成。

    话虽如此,这是分离代码的一种方法:

    第1部分:

    teams = []
    
    5.times do |i|
      puts "Please enter a UK football team:"
      teams << gets.chomp
    end
    

    第2部分:

    teams.sort!
    

    第3部分:

    5.times do |i|
      if i.even?
        teams[i].upcase!
      else
        teams[i].downcase!
      end
    end
    
    puts teams
    

答案 1 :(得分:0)

调整你的答案,试试这个:

football_team = []
5.times do |i|
  puts "Please enter a UK football team:"
  team = gets.chomp.downcase
  football_team << team
end

final_index = football_team.size - 1
football_team.sort!

(0..final_index).each do |i|

    if i.even?
        football_team[i] = football_team[i].upcase
    else
        football_team[i] = football_team[i].downcase
    end

end

p football_team