2017-07-13 32 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好点 - 更新我的答案。 –