2017-07-13 74 views
0

我正在編寫一個ruby腳本,我從命令行讀取命令並檢查它們是否正確。如果沒有,我會顯示比例錯誤。硬編碼字符串的最佳實踐

我的代碼如下所示:

if command == 0 
    puts "error one #{command}" 
elsif command == 1 
    puts "other error two #{command}" 
... 
end 

我有很多不同的錯誤串的,他們有它的Ruby代碼。 我想創建一個哈希,但我不能在錯誤字符串中添加ruby代碼。

有沒有更好的方法來管理(硬編碼)的錯誤字符串?

回答

2

如果代碼總是會在年底,那麼這可能會奏效:

Errors = { 
    0 => "error one", 
    1 => "other error two", 
}.freeze 

# later... 

command = 1 
puts "#{Errors.fetch(command)} #{command}" 
#=> other error two 1 

否則,你可以在錯誤代碼添加自定義的佔位符,後來替補:

Errors = { 
    0 => "error %{code} one", 
    1 => "%{code} other error two", 
}.freeze 

def error_str_for_code(code) 
    Errors.fetch(code) % { code: code.to_s } 
end 

# later... 

command = 1 
puts error_str_for_code(command) 
#=> 1 other error two 
+0

看到我更新的答案。 –

+0

嗯我認爲第二個答案解決了我的問題。謝謝。 –

+0

@ muistooshort好點 - 更新我的答案。 –