3

I have found the line_number passed to class_eval, module_eval and instance_eval doesn't match the line numbers reported by the error. This behaviour is not explained by the ruby-doc which says: (use instance_eval as an example)

the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

All these three methods class_eval, module_eval and instance_eval accepts two additional params to specify the filename and lineno parameters set the text for error messages.

this question has a practical demo for this behavior.

However, I have found the calculation of line numbers more complex than the explanation. Here is a demo

class Thing
  def add_method
    a = %{
      non_exist
    }
    instance_eval(a, 'dummy', 12)
  end
end

# error will raise to 15 instead of 12 which is specified 
puts Thing.new.add_method

The code above proves that the line_no param passed to instance_eval is not the line numbers reported by the error but is only related to the line_no.

I am wondering about the exact behavior of this params?

Community
  • 1
  • 1
steveyang
  • 9,178
  • 8
  • 54
  • 80

1 Answers1

1

As your snippet of the documentation states, lineno specifies the starting line number of the pseudo-file. The string you eval contains three lines, where the second line contains non_exist (%{} preserves line breaks).

When I execute your code, I get an error in line 14, not the 15 you receive. I would originally have expected to get 13, but it seems that the ruby parser will only "notice" the error on the next line, possibly looking for method arguments or something else to make sense of non_exists (I am not completely sure on that). If I insert another blank line (that contains no indentation) after non_exists, I get the expected 13.

Any lines inserted after %{ but before non_exists will increment the line number in the error by one, as should be expected.

Kolja
  • 1,197
  • 9
  • 17