I’m trying to parse some code with a ruby script, at some point I want to separate a String into substrings by using match:
frase = "EXTREM(TIME2,FRE,NFRE,SDV,DEL,RMG)"
frase.match(/(\w*)\((.*)\)/)
=> #<MatchData "EXTREM(TIME2,FRE,NFRE,SDV,DEL,RMG)" 1:"EXTREM" 2:"TIME2,FRE,NFRE,SDV,DEL,RMG">
it works as expected on irb, but when I put this in a script file (inside a function called procesa):
tmpo = extra.match(/(\w*)\s*\((.*)\)/)
puts "#{nombre} calls #{tmpo[1]} with #{tmpo[2]}"
I get this error:
`block in procesa': undefined method `[]' for nil:NilClass (NoMethodError)
from f2f90.rb:141:in `each_index'
from f2f90.rb:141:in `procesa'
from f2f90.rb:166:in `block in <main>'
from f2f90.rb:166:in `each'
from f2f90.rb:166:in `<main>'
I’ve searched this site and google with no luck, am I missing something?, I ended up putting extra.match(/(\w*)\s*(.*)/) and tmpo[2].sub("(","").sub(")","") instead but I don’t think its the best way of doing it, and I want to know why the first expression is wrong. Thanks in advance.
That error simply means there is no match. Perhaps if you print out
nombrebefore running the regex you might see why the regex didn’t match the string.