gpt4 book ai didi

ruby - 有没有办法将正则表达式捕获传递给 Ruby 中的 block ?

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:02 26 4
gpt4 key购买 nike

我有一个散列,其中一个 regex 作为键,一个 block 作为值。类似于以下内容:

{ 'test (.+?)' => { puts $1 } }

显然,不完全是,因为 block 被存储为 Proc,但这就是想法。

然后我有一个正则表达式匹配,看起来很像这样

hash.each do |pattern, action|
if /#{pattern}/i.match(string)
action.call
end
end

我的想法是将 block 存储在散列中,以便我将来更容易扩展,但现在 regex 捕获不会传递到 block 。有没有一种方法可以干净利落地支持我放入 regex 中的任意数量的捕获(例如,某些 regex 模式可能有 1 个捕获,其他模式可能有 3 个)?

最佳答案

如果您将匹配数据传递到您的进程中会怎样?

hash.each do |pattern, action|
if pattern.match(string)
action.call($~)
end
end

您的哈希将变为:

{ /test (.+?)/i => lambda { |matchdata| puts matchdata[1] } }

关于ruby - 有没有办法将正则表达式捕获传递给 Ruby 中的 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4719033/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com