Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending all regex matches as arguments

Tags:

ruby

I have a "table" of substitution rules stored in a hash, where each key is the rule and each value is a method that will take matched text and send those as arguments. Each method will return a string. Except I don't know how to send all matches. How can I fill in the comment in the send call to accomplish this?

Sub_Rules = {
   /N\[(\d+)\]/i          => :do_something,
   /N\[(\d+)\]\[(\d+)\]/i => :do_something_else
}

def do_something(*args)
  "something based on the args"
end

def do_something_else(*args)
  "something else based on the args"
end

text = "N[2]"
Sub_Rules.each {|rule, method|
  p text.gsub(rule) {send(method, #the matches?)}
}

If I wanted to hardcode it, I might do something like this:

text.gsub(/N\[(\d+)\]/i) { do_something($1) }
like image 269
MxLDevs Avatar asked May 21 '26 20:05

MxLDevs


1 Answers

If text.gsub(/N\[(\d+)\]/i) { do_something($1) } works, then this will too:

Sub_Rules.each do |rule, method|
  p text.gsub(rule) { send(method, $1) }
end

But I suspect that text.gsub(/N\[(\d+)\]/i) { do_something($1) } doesn't actually work seeing as it doesn't "send all matches" either. Instead you probably want

Sub_Rules.each do |rule, method|
  p text.gsub(rule) { send(method, $~.captures) }
end

which will send an array of the captures from each group in the regex.

like image 55
Andrew Marshall Avatar answered May 23 '26 11:05

Andrew Marshall