Search code examples
ruby-on-railsrubyif-statementguard-clause

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


How to use the guard clause in the following scenario? The msg is capturing info in 2 independent if-clauses.

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

Solution

  • Like this:

    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
    

    or to return as early as possible

    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
    

    Side note: Beware that the commonly accepted practice is for the ruby method names to end with ? when they return boolean value.