我正在ruby中编写一个case语句,它将获取当前文件名并查看文件名是否包含特定单词,但我的代码仍然遇到错误。
file = File.basename(__FILE__)
case file
when file.include? "daily"
HtmlCache.delete_all "daily = 1"
when file.include? "weekly"
HtmlCache.delete_all "weekly = 1"
end
任何人都知道如何搜索特定单词的文件名?
答案 0 :(得分:2)
使用if
代替case
。你的语法错误。
file = File.basename(__FILE__)
if file.include? "daily"
HtmlCache.delete_all "daily = 1"
elsif file.include? "weekly"
HtmlCache.delete_all "weekly = 1"
end
答案 1 :(得分:2)
试试这个:
file = File.basename(__FILE__)
case file
when /daily/
HtmlCache.delete_all "daily = 1"
when /weekly/
HtmlCache.delete_all "weekly = 1"
end
Ruby的case
语句匹配使用===
(所以case file when /daily/
调用/daily/ === file
),这在Regexes上可以正常工作。