在 ruby on rails 中使用 guard 子句用于多个独立的 if 子句

Using guard clause in ruby on rails for multiple independent if clause

下面的场景如何使用guard子句? 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

像这样:

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

或尽早return

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 方法名称在 return 布尔值时以 ? 结尾值。

我建议如下。

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