我遇到了一个问题-解决了一个我有.yml文件的任务,
time:
-
begin: :washington
end: :briston
min: 6
price: 3
-
begin: :briston
end: :dallas
min: 4
price: 2
-
begin: :dallas
end: :tokyo
min: 3.5
price: 3
-
begin: :tokyo
end: :chicago
min: 3.5
price: 3
和一列Train,我想在其中循环浏览.yml文件并提取必要的信息,并使用这些值(起点,终点,价格和持续时间)进行操作。
class Train
require 'yaml'
def initialize(time, line)
@time = YAML.load_file(time)
@line = YAML.load_file(line)
end
def calc(begin, end)
@time.select do |key, value|
puts key, value
end
end
end
在'calc'方法中,我定义了'select'方法来检索键和值,但它只是打印所有散列,如下所示:
time
{"begin"=>:washington, "end"=>:briston, "min"=>6, "price"=>3}
{"begin"=>:briston, "end"=>:dallas, "min"=>4, "price"=>2}
{"begin"=>:dallas, "end"=>:tokyo, "min"=>3.5, "price"=>3}
如何遍历此哈希以提取必要的数据?预先感谢!
答案 0 :(得分:1)
如果我明白这一点,请参阅变量@time
,查看我的评论:
@time = {"time"=>[{"begin"=>:washington, "end"=>:briston, "min"=>6, "price"=>3}, {"begin"=>:briston, "end"=>:dallas, "min"=>4, "price"=>2}, {"begin"=>:dallas, "end"=>:tokyo, "min"=>3.5, "price"=>3}, {"begin"=>:tokyo, "end"=>:chicago, "min"=>3.5, "price"=>3}]}
一种可重构的链接方式:
ary = @time['time']
start = :washington
stop = :tokyo
res = []
loop do
tmp = ary.find { |h| h['begin'] == start }
break unless tmp
res << tmp
start = tmp['end']
break if start == stop
end
然后您有res
:
#=> [{"begin"=>:washington, "end"=>:briston, "min"=>6, "price"=>3}, {"begin"=>:briston, "end"=>:dallas, "min"=>4, "price"=>2}, {"begin"=>:dallas, "end"=>:tokyo, "min"=>3.5, "price"=>3}]
例如要获取min
的总和:
res.sum { |h| h['min'] } #=> 13.5