可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the below code snippet:
line_sub = Regexp.new(/\s+|"|\[|\]/) tmp = Array.new # reading a file while line = file.gets ... tmp[0],tmp[1] = line.to_s.scan(/^.*$/).to_s.split('=') #remove unwanted characters tmp.collect! do |val| val.gsub(line_sub, "") end ... end
but when I run the code I get the error:
undefined method `gsub' for nil:NilClass (NoMethodError)
something seems to be wrong here:
tmp.collect! do |val| val.gsub(line_sub, "") end
Any idea?
回答1:
try this way for your solution
tmp.collect! do |val| if val.present? # or unless val.nil? val.gsub(line_sub, "") end end
回答2:
It means tmp[0] and/or tmp[1] is nil. Your
line.to_s.scan(/^.*$/).to_s.split('=')
didn't work as intended. Better check the result of that part.
By the way, line.to_s.scan(/^.*$/).to_s does not make sense. If you want to work on each line of the file, do
file.each_line do |l| ... l ... end
回答3:
One of the line you are reading is either empty, or it does not contain a '=' character.
#Then, you get either tmp[0], tmp[1] = ["only one element"] # => tmp[1] = nil #or tmp[0], tmp[1] = [] # both are nil.
回答4:
Add one condition like this
tmp.collect! do |val| if !val.nil? val.gsub(line_sub, "") end end
回答5:
If there should always be a value on each side of the "=" in the line, like "foo=bar" and not "foo=", then try something like this:
line.match(/(.+)=(.+)/ do |match| # do whatever you need with the match # if there is no match this block won't be executed tmp = match[1..2] tmp.map! do |string| string.gsub(/[\s"\[\]/, "") end end