Giorgio
Giorgio

Reputation: 5173

Ruby error: undefined method `[]’ for nil:NilClass

I am learning Ruby and I have a bug I cannot understand. I have a method that takes an array of strings (lines) and removes all lines up to a certain line containing a pattern. The method looks as follows:

def removeHeaderLines(lines)
  pattern = "..." # Some pattern.

  # If the pattern is not there, do not drop any lines.
  prefix  = lines.take_while {|line| (not line.match(pattern))}
  if prefix.length == lines.length then
    return prefix
  end

  # The pattern is there: remove all line preceding it, as well as the line
  # containing it.
  suffix  = (lines.drop_while {|line| (not line.match(pattern))}).drop(1)
  return suffix
end

This works fine and the resulting strings (lines) are displayed correctly on a web page I am generating.

Additionally, I want to remove all non-empty lines following the pattern. I have modified the method as follows:

def removeHeaderLines(lines)
  pattern = "..." # Some pattern.

  # If the pattern is not there, do not drop any lines.
  prefix  = lines.take_while {|line| (not line.match(pattern))}
  if prefix.length == lines.length then
    return prefix
  end

  # The pattern is there: remove all line preceding it, as well as the line
  # containing it.
  suffix  = (lines.drop_while {|line| (not line.match(pattern))}).drop(1)

  # Remove leading non-empty lines.
  # ADDING THIS INTRODUCES A BUG.
  body = suffix.drop_while {|line| (line != "")}
  return body
end

Very surprisingly (at least for me) this does not work. On the generated web page, instead of the content, I see the error message: Liquid error: undefined method `[]’ for nil:NilClass.

I cannot make much sense out of this message. As far as I understand, some code calling my code has tried to access a non-array object as if it were an array. But both versions of my method return an array of strings (both variables suffix and body are set to an array of strings), so why should there be a difference?

So, unfortunately, also due to my scarce knowledge of Ruby, I have no clue as to how to debug this problem.

Does anybody see any mistake in the above code? Alternatively, does anybody have any hints as to what can cause the error "undefined method `[]’ for nil:NilClass"?

EDIT

Additional information. I am extending code that I have not written myself (it comes from Octopress, file plugins/include_code.rb). The original rendering code looks like this:

def render(context)
  code_dir = (context.registers[:site].config['code_dir'].sub(/^\//,'') || 'downloads/code')
  code_path = (Pathname.new(context.registers[:site].source) + code_dir).expand_path
  file = code_path + @file

  if File.symlink?(code_path)
    return "Code directory '#{code_path}' cannot be a symlink"
  end

  unless file.file?
    return "File #{file} could not be found"
  end

  Dir.chdir(code_path) do

    ##################################
    # I have replaced the line below #
    ##################################
    code = file.read

    @filetype = file.extname.sub('.','') if @filetype.nil?
    title = @title ? "#{@title} (#{file.basename})" : file.basename
    url = "/#{code_dir}/#{@file}"
    source = "<figure class='code'><figcaption><span>#{title}</span> <a href='#{url}'>download</a></figcaption>\n"
    source += " #{highlight(code, @filetype)}</figure>"
    safe_wrap(source)
  end
end

I have replaced the line

code = file.read

with

code = linesToString(removeHeaderLines(stringToLines(file.read)))

where the two missing methods are:

def stringToLines(string)
  ar = Array.new
  string.each_line {|line| ar.push(line)}

  return ar
end

def linesToString(lines)
  s = ""
  lines.each {|line| s.concat(line)}

  return s
end

I hope this helps.

EDIT 2

Thanks to Hassan's hint (use the join method) I have found the problem! Parallel to the join method there exists a split method. So

"A\nB\n".split(/\n/)

gives

["A", "B"]

Whereas by using each_line (as I did), one gets each line with the '\n' at the end. As a consequence

suffix.drop_while {|line| (line != "")}

drops all lines. The result was an empty string that apparently crashes the library I am using. Thanks to Hassan for indicating a more idiomatic solution. I have now the following:

def removeHeaderLines(code)
  lines = code.split(/\r?\n/)
  pat   = /.../ # Some pattern.
  index = lines.index {|line| line =~ pat}
  lines = lines.drop(index + 1).drop_while {|line| line != ""} unless index.nil?

  lines.join "\n"
end

and it works fine.

Upvotes: 4

Views: 16774

Answers (2)

Michael Slade
Michael Slade

Reputation: 13877

That exception occurs when you attempt to use nil like an array (or hash):

irb(main):001:0> nil[0]
NoMethodError: undefined method `[]' for nil:NilClass
        from (irb):1
        from /home/mslade/rubygems1.9/bin/irb:12:in `<main>'

or use a variable as an array (or hash) when it has not been initialised:

irb(main):005:0> @b[0]
NoMethodError: undefined method `[]' for nil:NilClass
        from (irb):5
        from /home/mslade/rubygems1.9/bin/irb:12:in `<main>'

Look for where you have neglected to initalize the array, with something like @b = []

If you are not actually using an array, then it's possible that a funciton you are calling expects one. Scan through the stak dump given, starting at the top, until it mentions a line of your code. Then investigate that line to see what you might have missed.

Upvotes: 2

Hassan
Hassan

Reputation: 969

I don't know what cause the exception, but your code could be like this:

def remove_header_lines(lines)
  pattern = /some pat/
  index = lines.index {|lines| lines =~ pattern}

  lines = lines.drop(index+1).drop_while {|lines| line != ""} unless index.nil?

  lines.join
end

Upvotes: 0

Related Questions