有没有更优雅的方式来执行多重包含? ruby 中的选择?

Is there a more elegant way to perform a multiple include? selection in ruby?

我昨晚在一个项目中遇到了这个问题,当时我正在编写一个帮助程序来根据文件扩展名选择一个图标,并且想知道是否有更好的(更多"ruby")处理它的方法?

目前的代码是这样的:

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

当然,那是行不通的。虽然它更容易阅读,所以我想知道我是否错过了对选项集合进行多重比较的其他方法,这些方法可以恢复我的代码的一些优雅和可读性?

你几乎做对了。只需去掉方括号和 include? 即可。我认为星号也不是必需的,因为 File.extname returns 扩展名只有一个点。

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

您可以使用散列:

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"