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) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With