将输出排列在不同的行中

时间:2011-10-12 09:08:21

标签: arrays sorting input

只需要进行一些抛光工作..

command = ""
names = []
while command != "exit"
puts 'please enter names seperated by a space: '

 command = gets.chomp!

 if command == "quit"
   names.sort! do|a,b| a.upcase <=> b.upcase end         # use {...} for do\end, in a single entry rather then multiple
    names.each_with_index do |name, index|
   if index % 2 == 0
       puts "#{name}", "\n"
      else
      puts "#{name.reverse}", "\n"
  end
 end
  else
    names << command
  end
end

所以这个程序所做的是显示用户输入的多个名称。我不能让它做的是在彼此之下显示名称。例如。 抢 法案 露西 劈 ... 它然后向后显示每个第二个名称,并在这样的

下显示它们

抢劫

纸币

斩波

==

为llib

POHC。

lolmy大脑煮熟了什么建议??

1 个答案:

答案 0 :(得分:0)

我将如何做到这一点:

names = []
while true
  puts 'please enter names seperated by a space: '
  command = gets.chomp
  break if command == 'exit' #exit loop if exit is entered
  command.split(' ').each {|a| names.push(a)} # split up each word with space as delimiter and insert into the array
end


temp = []
names.each do |each| #cycle thru array
  puts each # print each entry
  temp.push(each) if names.index(each).odd? #if entry is odd then add to temp array
end
puts '======'
temp.each {|each| puts each.reverse} #print each entry reversed

如果你愿意,我可以尝试修复你的......