Ruby: search filename for keyword
I am writing a case statement in ruby that will take the current filename and see if the filename includes a particular word, but I keep running in开发者_Python百科to errors with my code.
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
Anyone know how to search the filename for a particular word?
Use if
instead of case
. You have just wrong syntax.
file = File.basename(__FILE__)
if file.include? "daily"
HtmlCache.delete_all "daily = 1"
elsif file.include? "weekly"
HtmlCache.delete_all "weekly = 1"
end
Try this:
file = File.basename(__FILE__)
case file
when /daily/
HtmlCache.delete_all "daily = 1"
when /weekly/
HtmlCache.delete_all "weekly = 1"
end
Ruby's case
statement matches using ===
(so case file when /daily/
invokes /daily/ === file
), which works as you'd like on Regexes.
精彩评论