【问题标题】:Determine which value was selected确定选择了哪个值
【发布时间】:2018-11-20 03:31:17
【问题描述】:

我有三个数值变量:on_the_grounddouble_round_trippoint_to_pointprice 函数根据一些简单的逻辑返回其中之一。

下面是它目前的工作方式。

def price
  return on_the_ground if date_range == 1

  values = [
    on_the_ground,
    double_round_trip
  ]

  if !turbo? && !vlj?
    values.push(point_to_point)
  end

  values.compact.min
end

我想要一个函数,它可以根据应该返回的值返回一个符号。例如:

def price_name
  return :on_the_ground if date_range == 1
  ... etc...
end

【问题讨论】:

  • 一个方法可以返回一个Symbol,就像上面的price_name方法一样。究竟是什么问题?
  • 我需要得到values.compact.min选择的变量名。
  • 为此,您需要值和名称之间的映射。使用Hash 来做到这一点。

标签: ruby algorithm logic


【解决方案1】:

如果我明白你的意思,为什么不使用数组?

def price_name_for date_range
  [:on_the_ground, :double_round_trip, :point_to_point][date_range-1]
end

price_name_for 1 #=> :on_the_ground
price_name_for 2 #=> :double_round_trip
price_name_for 3 #=> :point_to_point

【讨论】:

  • 比这复杂一点。点对点价格在数组中存在一些条件。我在下面提供了一个答案,展示了我是如何解决它的。
【解决方案2】:

你可以用例

case values
  when double_round_trip
    return :double_round_trip
  when on_the_ground 
...

https://www.rubyguides.com/2015/10/ruby-case/

【讨论】:

    【解决方案3】:

    我最终使用了:

    price_options.key(price) # double_round_trip
    

    【讨论】:

    • 我在评论中建议使用Hash
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多