【发布时间】:2019-05-19 02:16:09
【问题描述】:
Ruby Wizardry Chapter 4 一书包含以下示例程序
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where ya headin', friend?"
destination = gets.chomp
if stops.include? destination
puts "I know how to get to #{destination}! Here's the station list:"
stops.each do |stop|
puts stop
break if stop == destination
end
else
puts "Sorry, we don't stop at that station. Maybe another time!"
we_wanna_ride = false
end
end
接下来会带来一些额外的挑战:
“如果乘客在火车上朝另一方向行驶(例如,从 Mal Abochny 到 East Bumpspark)怎么办?如何更新程序以双向工作?更棘手的是,如果火车路线是大圆圈(意思是如果乘客从 East Bumpspark 到 Mal Abochny,Mal Abochny 之后的下一站应该又是 East Bumpspark)?如果乘客想去所有地方,你如何更新程序以打印出正确的火车停靠点列表绕圈的路?”
有人知道如何在这里进行吗?我是一个初级程序员,所以任何帮助将不胜感激。这是我到目前为止的进展。我想我会从用户那里得到一个departure,然后使用 to.i 将输入变成一个整数。然后我可以使用整数值与数组中的索引位置进行比较。如果骑手想朝相反的方向前进,我可以使用 stop.each.reverse 之类的东西以相反的顺序打印出数组项。
we_wanna_ride = true
stops = ["East Bumpspark(1)", "Endertromb Avenue(2)", "New Mixico(3)", "Mal Abochny(4)"]
puts "#{stops}"
while we_wanna_ride
print "Select a destination number"
destination = gets.chomp.to_i
print "Select a departure number"
departure = gets.chomp.to_i
if departure <= destination
stops.each do |stop|
puts stop
break if stop == destination
end
else puts "Sorry"
we_wanna_ride = false
end
end
【问题讨论】:
-
如果您发布您所做的尝试而不是完全开放式的问题,通常更容易获得答案。试一试并编辑您的问题,包括您的尝试、您期望的工作以及发生了什么。
-
谢谢@Max!我希望我的新描述更有用。干杯
标签: arrays ruby loops while-loop