首页 > 解决方案 > 使用匹配方法匹配动态数据

问题描述

我试图在 match 方法的帮助下匹配动态路由,但它不起作用。

["payment", "portal", "animation"].each do |arg|
    define_method("profile_#{arg}") do 
        self.path.match("/users/\d+/#{arg}")
    end
end

因此,此代码 self.path.match("/users/\d+/#{arg}") 不适用于插值。

而如果我做类似下面的事情,那么它就可以工作。那么,有没有办法动态匹配数据

self.path.match('/users/\d+/payment')
self.path.match('/users/\d+/portal')
self.path.match('/users/\d+/animation')

标签: ruby-on-railsregexrubyruby-on-rails-5

解决方案


您可以在正则表达式文字本身内进行插值。

?> s = "payment"
=> "payment"
>> %r(/users/\d+/#{s})
=> /\/users\/\d+\/payment/

推荐阅读