我让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
答案 0 :(得分: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
可能是常数,但通常不是一个好主意。另请注意,您的循环变量是错误的。
答案 1 :(得分: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