Skip to content

Instantly share code, notes, and snippets.

@IceTimux

IceTimux/e19v7.md

Last active Dec 4, 2020
Embed
What would you like to do?

~Programming | Replacing switch statements with lookup tables


consider the follwoing switch statement. It translates a color string from english to Papiamentu.

def color_mapper(color)
  case color
  when 'yellow'
    'hel'
  when 'blue'
    'blou'
  when 'red'
    'kòrá'
  else
    'N/A' 
  end
end

color_mapper('yellow') # "hel"
color_mapper('green') # "N/A"

As you can see this looks pretty ugly. Let's replace it with a Lookup table.

@colors_table = {
  'yellow' => 'hel',
  'blue' => 'blou',
  'red' => 'kòrá'
}

def color_mapper(color)
  @colors_table[color] || 'N/A'
end

color_mapper('yellow') # "hel"
color_mapper('green') # "N/A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment