Write the best switch function?
I was having unsuccessful attempts with Hash-es for this problem due to a suboptimal specification that was provided to me (which means: changing the business specification during development).
Hashes are fine as long as you don't need to write something more complex than a single value. If you need to change these single values to methods, you must rewrite everything, since the hash takes the value of the methods, invoking them when the hash is determined. And if the method later returns a value, the hashes will not be changed.
And it remains readable in English :-)
def readable_status(status)
case status
when "1" then "go" end
when "2" then "stop" end
when "3" then "die" end
end
end
source to share
If a hash is defined inside a method, the hash (and every line in it) is recreated every time the method is called. Defining a constant prevents this from happening; using a method to access values is still flexible as @Phrogz said.
READABLE_STATUS_TABLE = {'1'=>'go', '2'=>'stop', '3'=>'die'}
def readable_status(status)
READABLE_STATUS_TABLE[status]
end
source to share