Reputation: 21616
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?
Upvotes: 2
Views: 17152
Reputation: 2541
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
Upvotes: 0
Reputation: 1815
Add one condition like this
tmp.collect! do |val|
if !val.nil?
val.gsub(line_sub, "")
end
end
Upvotes: 2
Reputation: 6036
try this way for your solution
tmp.collect! do |val|
if val.present? # or unless val.nil?
val.gsub(line_sub, "")
end
end
Upvotes: 6
Reputation: 15010
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.
Upvotes: 1
Reputation: 168199
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
Upvotes: 1