我昨晚在一个项目中遇到了这个问题,同时根据文件扩展名编写帮助来选择一个图标,并且想知道是否有更好的(更“红宝石”)方式来处理它?</ p >
目前代码如下:
def choose_icon(myfile)
icon = "default-icon"
if ["*.doc","*.docx",".txt","*.dot"].include? File.extname(myfile)
icon = "doc-icon"
end
if ["*.xls","*.xlsx","*.xlt"].include? File.extname(myfile)
icon = "sheet-icon"
end
if ["*.mp3","*.aac","*.aiff","*.wav"].include? File.extname(myfile)
icon = "audio-icon"
end
if ["*.mov","*.m4a","*.wmv"].include? File.extname(myfile)
icon = "movie-icon"
end
icon # return the chosen icon
end
这对我来说感觉有点笨拙和不优雅,我很难在Ruby中找到更好的方法。
(注意:上面的例子真的很简单,实际的代码要长得多,看起来也不整齐。)
如果' case '结构可以这样工作,那真的很酷:
def choose_icon(myfile)
case File.extname(myfile)
when ["*.doc","*.docx",".txt","*.dot"].include?
"doc-icon"
when ["*.xls","*.xlsx","*.xlt"].include?
"sheet-icon"
when ["*.mp3","*.aac","*.aiff","*.wav"].include?
"audio-icon"
when ["*.mov","*.m4a","*.wmv"].include?
"movie-icon"
else
"default-icon"
end
end
但当然,这不起作用。它阅读起来要容易得多,所以我想知道我是否错过了一些其他的方法来对一组选项进行多重比较,这些选项会为我的代码恢复一些优雅和可读性?
答案 0 :(得分:3)
你几乎做对了。只需不要使用方括号和include?
,它就可以了。我认为星号不一定是必要的,因为File.extname
只返回一个点的扩展名。
def choose_icon(myfile)
case File.extname(myfile)
when '.doc', '.docx', '.txt', '.dot'
'doc-icon'
when '.xls', '.xlsx', '.xlt'
'sheet-icon'
when '.mp3', '.aac', '.aiff', '.wav'
'audio-icon'
when '.mov', '.m4a', '.wmv'
'movie-icon'
else
'default-icon'
end
end
答案 1 :(得分:2)
您可以使用哈希:
h = [*(%w| .doc .docx .txt .dot |).product(["doc-icon"]),
*(%w| .xls .xlsx .xlt |).product(["sheet-icon"]),
*(%w| .aac .aiff .wav |).product(["audio-icon"]),
*(%w| .mov .m4a .wmv |).product(["movie-icon"])].to_h
#=> {".doc"=>"default-icon", ".docx"=>"default-icon",
# ".txt"=>"default-icon", ".dot"=>"default-icon",
# ".xls"=>"sheet-icon" , ".xlsx"=>"sheet-icon",
# ".xlt"=>"sheet-icon" , ".aac"=>"audio-icon",
# ".aiff"=>"audio-icon" , ".wav"=>"audio-icon",
# ".mov"=>"movie-icon" , ".m4a"=>"movie-icon",
# ".wmv"=>"movie-icon"}
h.default = "default-icon"
h[File.extname("myfile.wav")]
#=> "audio-icon"
h[File.extname("./mydir/myfile.abc")]
#=> "default-icon"