vendredi 8 avril 2016

Ruby best practices should you use if, case or hash to make conversion methods

All options are valid but which has the best performance, or is the preferred style?

hash

  def codify(pet)
    hash = {
      'dog' => 'D',
      'cat' => 'C',
      'bird' => 'B',
    }
    return hash[pet] || 'U'
  end 

inline

  def codify(pet)
    return 'D' if pet == 'dog'
    return 'C' if pet == 'cat'
    return 'B' if pet == 'bird'
    return 'U'
  end

if else

  def codify(pet)
    if pet == 'dog'
      return 'D'
    elsif pet == 'cat'
      return 'C'
    elsif pet == 'bird'
      return 'B'
    else
      return 'U'
    end
  end

case

  def codify(pet)
    case pet
    when 'dog'
      return 'D'
    when 'cat'
      return 'C'
    when 'bird'
      return 'B'
    else
      return 'U'
    end
  end

Also stackoverflow needs some more detail so... Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.

Aucun commentaire:

Enregistrer un commentaire