我从事有关日程安排的任务,并有类和.yml文件,我想在其中检索数据作为“起点”,“终点”,“价格”等。在我的课堂上,我有方法,我想在其中确定电台是否等于用户选择:
class Train
require 'yaml'
def initialize(time)
@time = YAML.load_file(time)
end
def calc(begin:, end:)
ary = @time['time']
start = begin
stop = end
res = []
loop do
tmp = ary.find { |h| h['begin'] == start }
break unless tmp
res << tmp
start = tmp['end']
break if start == stop
end
end
end
但是它总是在有条件的情况下失败
break unless tmp
例如,如果写入实例变量
a = Train.new("my_path_to yml")
a.calc(begin: ':washington', end: ':tokyo')
它什么也不执行。即使我重构循环块并编写“ for”迭代器,它也会抛出“ else”条件:
for i in ary
if i['begin'] == 'washington'
puts "good"
else
puts "no way"
end
end
这是我的.yml文件
time:
-
begin: :washington
end: :briston
time: 6
price: 3
-
begin: :briston
end: :dallas
time: 4
price: 2
-
begin: :dallas
end: :tokyo
time: 3.5
price: 3
-
begin: :tokyo
end: :chicago
time: 3.5
price: 3
-
begin: :chicago
end: :dellawer
time: 3.5
price: 3
谢谢!
答案 0 :(得分:4)
尝试此更改,检查代码中的注释:
def calc(begin_:, end_:) # <-- don't call variables begin or end, they are reserved words
ary = @time['time']
start = begin_
stop = end_
res = []
loop do
tmp = ary.find { |h| h['begin'] == start }
break unless tmp
res << tmp
start = tmp['end']
break if start == stop
end
res # <-- return something
end
呼叫为:
train.calc(begin_: :washington, end_: :tokyo)
#=> [{"begin"=>:washington, "end"=>:briston, "time"=>6, "price"=>3}, {"begin"=>:briston, "end"=>:dallas, "time"=>4, "price"=>2}, {"begin"=>:dallas, "end"=>:tokyo, "time"=>3.5, "price"=>3}]
ary.each do |i| # for i in ary <-- pythonic! :)
if i['begin'] == :washington # <-- should be a symbol to pass, not a string
puts "good"
else
puts "no way"
end
end