0

我让 Ruby 要求用户五次输入名称,并希望每行都吐出答案,以大写和小写交替出现。下面是我所做的,它打印出每个名字两次,一个大写一个小写。但我只想让每一行在大写和小写之间交替。我希望我在这里有意义...

Football_team = []

5.times do 
    puts "Please enter a UK football team:"
    Football_team << gets.chomp
end

Football_team.each do |Football_team|
    puts team.upcase
    puts team.downcase
end
4

2 回答 2

2
football_team = []

5.times do 
  puts "Please enter a UK football team:"
  football_team << gets.chomp
end

football_team.each_with_index do |team, index|
  if index.even?
    puts team.upcase
  else
    puts team.downcase
  end
end

请注意,您应该只对常量使用以大写字母开头的标识符。虽然Football_team可能是一个常数,但通常不是一个好主意。另请注意,您的循环变量是错误的。

于 2015-05-12T01:00:37.013 回答
0

你真的不需要两个循环。您可以一次性完成所有操作。见下文

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

或者,相同的解决方案但简写:

football_team = []

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

puts football_team
于 2015-05-12T06:07:25.547 回答