第一篇文章。
下面的代码有效,按字母顺序排列我的答案,但我很难为我的程序添加条件。
我认为我需要包含一个if / else语句,以便其他所有答案都是大写的。
ie:names = [" Bob"," Joe"," Bill"," Fred"] 期望的输出=
BILL
鲍勃
FRED
乔
names = []
4.times do
puts "Please enter your amigo's names:"
names << gets.chomp
end
SortNames = names.sort
SortNames.each do |name|
puts "There once was a person named " + name + "."
end
非常感谢你的帮助!!
答案 0 :(得分:1)
formatted = []
names.each_slice(2) do |odd, even|
formatted << odd.upcase
formatted << even.downcase if even
end
答案 1 :(得分:0)
names.sort.each_with_index do |name, index|
formatted_name = index.odd? ? name : name.upcase
puts "There once was a person named #{formatted_name}."
end
答案 2 :(得分:0)
我喜欢这个:
["Bob", "Joe", "Bill", "Fred"].sort.each_with_index.map{|x,n| n.even? ? x.downcase : x.upcase}
或
names = ["Bob", "Joe", "Bill", "Fred"]
puts names.sort.each_with_index.map{|x,n| n.even? ? x.downcase : x.upcase}
输出:
bill
BOB
fred
JOE
不确定是否要先对其进行排序。删除将为您提供原始订单的.sort
。