undefined method `gsub' for nil:NilClass (NoMethodError

匿名 (未验证) 提交于 2019-12-03 01:03:01

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!