Using Hash Tables Instead of Switch

by Sep 8, 2009

You may have already used Switch to translate input and output values like this:

function Get-Name($number) {
switch ($number) {
1 { "One" }
2 { "Two" }
3 { "Three" }
default { "Other" }
}
}

For translation jobs, a hash table could be more efficient:

function Get-Name($number) {
$translate = @{
1 = "One"
2 = "Two"
3 = "Three"
}
$translate[$number]
}

Get-Name 1
Get-Name 2

Twitter This Tip! ReTweet this Tip!