Write the best switch function?
I am new to Ruby.
How can I write this function better? I can use a hash table instead.
def readable_status(status)
if status == "1"
return "go"
end
if status == "2"
return "stop"
end
if status == "3"
return "die"
end
end
If you want to use hash (as per your question), you can do:
def readable_status(status)
readable = { "1" => "go", "2" => "stop", "3" => "die" }
readable[status] || "default value"
end
What about
def readable_status(status)
%w{go stop die}[status.to_i - 1]
end
sure just use
def readable_status(status)
m = {'1' => 'go', '2' => 'stop', '3' => 'die'}
m[status]
end
you can do this oneliner if you like:
...
{'1' => 'go', '2' => 'stop', '3' => 'die'}[status]
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
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