【问题标题】:Using guard clause in ruby on rails for multiple independent if clause在 ruby​​ on rails 中为多个独立的 if 子句使用保护子句
【发布时间】:2020-12-11 07:33:58
【问题描述】:

如何在以下场景中使用保护子句? msg 在 2 个独立的 if 子句中捕获信息。

def edible?(food_object)

    edible_type = ['fruit','vegetable','nuts']
    food_list  = ['apple','banana','orange','olive','cashew','spinach']

    food = food_object.food
    type = food_object.type
   
   msg = ''
   if edible_type.include?(type)
     msg += 'Edible : '
   end

   if food_list.include?(food)
     msg += 'Great Choice !'
   end

end

【问题讨论】:

    标签: ruby-on-rails ruby if-statement guard-clause


    【解决方案1】:

    像这样:

    def edible?(food_object)
      edible_type = ['fruit','vegetable','nuts']
      food_list  = ['apple','banana','orange','olive','cashew','spinach']
      food = food_object.food
      type = food_object.type
      
      msg = ''
      msg += 'Edible : ' if edible_type.include?(type)
      msg += 'Great Choice !' if food_list.include?(food)
    end
    

    或尽早返回

    def edible?(food_object)
      edible_type = ['fruit','vegetable','nuts']
      food_list  = ['apple','banana','orange','olive','cashew','spinach']
      food = food_list.include?(food)
      type = edible_type.include?(type)
      msg = ''
      return msg unless food || edible
      msg += 'Edible : ' if type
      msg += 'Great Choice !' if food
    end
    

    旁注:请注意,普遍接受的做法是 ruby​​ 方法名称在返回布尔值时以 ? 结尾。

    【讨论】:

    • 成功了。非常感谢代码和建议!
    • 如果food_list.include?(food) == false,您的解决方案将返回nil。也似乎“可食用:”是一个奇怪的反应,所以edible_type.include?(type) && food_list.include?(food) ? "Edible: Great Choice!" : "" 可能更有意义
    • 你显然已经看到了@engineersmnky 的评论,那你为什么不更正你的代码呢?
    【解决方案2】:

    我建议如下。

    EDIBLE_TYPE = ['fruit','vegetable','nuts']
    FOOD_LIST   = ['apple','banana','orange','olive','cashew','spinach']
    
    def edible?(food_object)
      "%s%s" % [EDIBLE_TYPE.include?(food_object.type) ? 'Edible : ' : '',
                FOOD_LIST.include?(food_object.food)   ? 'Great Choice !' : '']
    end
    

    我们可以通过稍微修改方法来测试一下。

    def edible?(type, food)
      "%s%s" % [EDIBLE_TYPE.include?(type) ? 'Edible : ' : '',
                FOOD_LIST.include?(food)   ? 'Great Choice !' : '']
    end
    
    edible?('nuts', 'olive')     #=> "Edible : Great Choice !" 
    edible?('nuts', 'kumquat')   #=> "Edible : " 
    edible?('snacks', 'olive')   #=> "Great Choice !" 
    edible?('snacks', 'kumquat') #=> "" 
    

    方法的操作行也可以写成:

    format("%s%s", EDIBLE_TYPE.include?(food_object.type) ? 'Edible : ' : '',
                   FOOD_LIST.include?(food_object.food)   ? 'Great Choice !' : ''])
    

    "#{EDIBLE_TYPE.include?(food_object.type) ? 'Edible : ' : ''}#{FOOD_LIST.include?(food_object.food) ? 'Great Choice !' : ''}"
    

    Kernel#format

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      相关资源
      最近更新 更多