just a bit of polish work needed..
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
so what this progam does is display a number of names that where entered by the user. what i cant get it to do is display the names under each other. eg. rob bill lucy chop ... its开发者_StackOverflow中文版 then to display every second name backwards and to display them under like this
rob
bill
lucy
chop
======
llib
pohc.
lolmy brain is cooked any suggestions??
Here is how I would do it :
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
I can try to fix yours if you want...
精彩评论