我建议以下。
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。