如何通过从输入用户获取的值从数组中选择元素(获取)

时间:2019-02-25 21:07:57

标签: ruby

enter code here大家晚上好 我想让用户从Red_line

编写start_station

例如在这种情况下

“启动站” “公园街” 您将通过这些站 南站 公园街 肯德尔 中央。 车站总数: 4。

问题是

当我尝试使用户输入的值不起作用时(例如您在 start_station str 输入中看到的内容,但是当我不输入时)选择工作正常就像您在 start_station

中看不到的一样

我希望这很清楚,谢谢您的时间

subway =
 {
     "Red_line":["South Station","Park Street","Kendall","Central","Harvard","Porter","Davis","Alewife"]
}

puts"put ur start Station "
 sta = gets.chomp.to_s #<<==== this my attempted to use sta to make it like input  user
puts sta

start_station = subway[:Red_line].index(sta) # <<=== you can see that I put sta as index of subway array
puts start_station

end_station = subway[:Red_line].index("Central")

total_point_in_redLine = subway[:Red_line][start_station..end_statio] #name of points
total_number_in_redLine = subway[:Red_line][start_station..end_statio].length #number of station

puts "you will pass these Stations"
puts total_point_in_redLine
puts "total number of Stations is "
puts total_number_in_redLine

1 个答案:

答案 0 :(得分:0)

# DEFINE SUBWAY
subway =
 {
     "Red_line":["South Station","Park Street","Kendall","Central","Harvard","Porter","Davis","Alewife"]
}

# GET START STATION FROM USER
puts"put ur start Station "
sta = gets.chomp.to_s 
puts sta

# GET START STATION INDEX
start_station = subway[:Red_line].index(sta)

# GET END STATION INDEX
end_statio = subway[:Red_line].index("Central")

# BUG: 
# THIS ONLY WORKS IF END STATION IS AFTER START
# SO ANY STATION AFTER CENTRAL IS A BUG
total_point_in_redLine = subway[:Red_line][start_station..end_statio] 
total_number_in_redLine = subway[:Red_line][start_station..end_statio].length 

puts "you will pass these Stations"
puts total_point_in_redLine
puts "total number of Stations is "
puts total_number_in_redLine

该错误是由于用于访问[start_station..end_statio]数组中值subway[:Red_line]的范围需要从低到高,所以该范围中的第一个值不能大于最后一个。当start_station为5且end_station为3时,范围为subway[:Red_line][5..3],您需要将其反转subway[:Red_line][3..5]

要解决此错误,您可以使用条件

if start_station <= end_statio
  total_point_in_redLine = subway[:Red_line][start_station..end_statio] 
  total_number_in_redLine = subway[:Red_line][start_station..end_statio].length 
else 
  total_point_in_redLine = subway[:Red_line][end_statio..start_station] 
  total_number_in_redLine = subway[:Red_line][end_statio..start_station].length 
end