如何在以下场景中使用guard子句?msg
在两个独立的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
或尽早返回
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方法名称返回布尔值时,它们以?
结尾。
我建议如下。
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 !' : ''}"
请参阅内核#格式。