如果我知道另一个哈希的键,如何从哈希中获取值

时间:2019-04-26 08:41:42

标签: ruby

当我拥有实例方法和哈希值时,我陷入了麻烦,我想使用方法的属性遍历该哈希值以获取值。 例如,我有方法:

class M
  def initialize(time, line)
    @time = YAML.load_file(time)
    @line = YAML.load_file(line)
  end

  def sum(from_station:, to_station:)
    array = @time['timing'] 
    lines = @line['lines']          
    line = @line['stations'] 
    from_station_line = line[from_station.to_s]
    to_station_line = line[to_station.to_s]
    str = from_station
    stop = to_station
    result = []
    result2 = []
    result3 = []
    time = 0
    if from_station_line[0] == to_station_line[0]
      loop do
      tmp = array.find{|x| x['start'] == str}
      break unless tmp
      result << tmp
      str = tmp['end']
      time = result.sum{|b| b['time']}
      break if str == stop
      end
      puts time
    else
      case array
    end
    p time, result2
   end
  end
end

a = M.new("./config/time.yml", "./config/config.yml")
a.sum(from_station: :tokyo, to_station: :milan)

和config.yml工作站:

lines:
  - :black
  - :red
  - :yellow
stations:
  tokyo:
    - :black
  chicago:
    - :black
  amster:
    - :black
    - :red
  prague:
    - :black
  milan:
    - :black
    - :red
  bayern:
    - :black
    - :yellow

这是time.yml

 timing:
  -
    start: :tokyo
    end: :chicago
    time: 6
    price: 3
  -
    start: :chicago
    end: :amster
    time: 4
    price: 2
  -
    start: :amster
    end: :prague
    time: 3.5
    price: 3
  -
    start: :bayern
    end: :milan
    time: 3.5
    price: 3
  -
    start: :milan
    end: :roma
    time: 3.5
    price: 3
  -

我需要选择from_station:to_station:是否在同一分支上(黑色或红色,或两者)。我能做到吗? 换句话说:如果用户选择从站点“:tokyo”移至站点“:milan”,我需要知道这两个站点是否在同一行(:黑色,红色或黄色)。因此要知道我需要管理config.yml文件,并循环访问“:tokyo” [black] ==“:milan [yellow]

1 个答案:

答案 0 :(得分:0)

通常在Ruby中,您不会使用loopbreak语句。 Enumerable模块将为您完成大部分工作。可能需要一点时间来习惯它,但随后它会自然而然地使您快速熟悉很多东西。请注意,其他编程语言也采用类似的概念。

  a = line.select {|k,v| k.to_sym == from_station}  #how to implement this condition?
  b = line.select {|k,v| k.to_sym == to_station}#

您可以在哈希中进行典型的查找,这可以通过

完成
def sum(from_station, to_station)
  from_station_colors = @lines[from_station]
  to_station_colors   = @lines[to_station]

  if (from_station_colors.nil? || from_station_colors.empty?)
    # from_station not found
  end
  # ...
end

timing中的查找有点复杂:

require 'yaml'

timings = YAML::load_file('timing.yml')['timing']

from_station = :tokyo
to_station = :chicago

# "t" (a timing entry) might be nil, thus the first select
# Note that there are other handy functions to make this more readable
# (left as an exercise)
transit = timings.select{|t| t}.select do |timing|
  # if the following line evaluates to "true", select this entry
  timing['start'] == from_station && timing['end'] == to_station
end

puts transit # {"start"=>:tokyo, "end"=>:chicago, "time"=>6, "price"=>3}

您的其他问题(找出这些位置是否共享相同的“颜色”)可能应该分别提出。不知何故,这个任务听起来像是一项家庭作业。

欢迎来到StackOverflow!请考虑对您的下一个问题尽可能地精确-将示例减少到“最少”。