我想在一个导轨应用滤波器之前设置如下:在Ruby中的引号中使用通配符运算符?
before_filter :set_instance_variables, :unless => :active_pages?
def active_pages?
params[:controller] == "admin/*"
end
其中我想它有*表示任何字,使得该方法对任何与启动控制器检查'管理/'。我认为星号可能是一张通配符和工作,但似乎并不奏效。我怎样才能做到这一点?
我想在一个导轨应用滤波器之前设置如下:在Ruby中的引号中使用通配符运算符?
before_filter :set_instance_variables, :unless => :active_pages?
def active_pages?
params[:controller] == "admin/*"
end
其中我想它有*表示任何字,使得该方法对任何与启动控制器检查'管理/'。我认为星号可能是一张通配符和工作,但似乎并不奏效。我怎样才能做到这一点?
def active_pages?
%r{^admin/.*} =~ params[:controller]
end
它使用=~
到一个字符串匹配正则表达式,并%r{}
的正则表达式,因为你的模式包含/
(在//
符号将更难读)。
使用一些正规表达式
def active_pages?
params[:controller] =~ /^admin\/\w+$/
end
这个问题有几种解决方案。从我的角度来看,不涉及正则表达式最简单的办法是String#index
def active_pages?
params[:controller].index("admin/") == 0
end
另一种解决方案是一个正则表达式,如其他用户已经建议。
def active_pages?
params[:controller] =~ %r{^admin/.*}
end
我个人更喜欢在这种情况下的index
解决方案。作为奖励,index
看起来比正则表达式快一点(实际上差别不是很明显)。
这是一个基准。
require 'benchmark'
array = (1..1000000).map { "string#{rand(4)}/string" }
Benchmark.bmbm do |x|
x.report("index") { array.each { |item| item.index("string2") == 0 } }
x.report("regex") { array.each { |item| item =~ %r{^string2/.*} } }
end
这就是结果。
$ ruby index.rb
Rehearsal -----------------------------------------
index 0.560000 0.020000 0.580000 ( 0.582749)
regex 1.000000 0.020000 1.020000 ( 1.015548)
-------------------------------- total: 1.600000sec
user system total real
index 0.570000 0.000000 0.570000 ( 0.576076)
regex 0.970000 0.020000 0.990000 ( 0.988980)
+1,但有正则表达式第一次感觉就像尤达条件;-) –