0

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

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
4

2 回答 2

2

像这样:

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​​ 方法名称在返回布尔值时以它们结尾。

于 2020-12-11T07:40:20.730 回答
1

我建议以下。

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 !' : ''}"

请参阅内核#format

于 2020-12-12T00:00:07.427 回答