yml中节点数量未知 - 如何解析?

时间:2015-01-10 02:25:20

标签: ruby-on-rails ruby ruby-on-rails-4 yaml

在一个应用程序中我有这个:

def get_debt_for_month(api_requests_count)
  case api_requests_count
  when 0..50
    5
  when 50..100
    9
  when 100..200
    13
  # and so on
  end
end
显然,拥有硬编码并不是一个好主意。我该怎么办?我认为最好的方法是价格应该转移到yml文件,但我如何动态解析它,因为案件的数量是不知道的并且可以变化?

1 个答案:

答案 0 :(得分:2)

如果范围内没有间隙,只需使用起始值...

# data.yml
0: 5
51: 9
101: 13

然后你的方法......

def get_debt_for_month(api_request_count)
  thresholds = YAML.load_file('data.yml')
  thresholds.sort.select{|e| e[0] <= api_request_count}.last[1]
end
相关问题