Home > OS >  Ruby ERB class gives "undefined local variable or method", but erb parses fine
Ruby ERB class gives "undefined local variable or method", but erb parses fine

Time:10-08

With this ERB template in a file test.erb:

% for i in 0..1
  foo<%=i%>;
% end

erb parses it as expected:

$ erb test.erb
    foo0;
    foo1;

Trying to use Ruby's ERB class as follows, in test.rb:

require 'erb'

e = ERB.new(File.read("test.erb"))
File.open("test.out", 'w') do |f|
    f.write e.result(binding)
end

Gives:

$ ruby test.rb
(erb):2:in `block in <main>': undefined local variable or method `i' for main:Object (NameError)
        from <...>/lib/ruby/1.9.1/erb.rb:838:in `eval'
        from <...>/lib/ruby/1.9.1/erb.rb:838:in `result'
        from test.rb:5:in `block in <main>'
        from test.rb:4:in `open'
        from test.rb:4:in `<main>'

and in a more recent Ruby version:

$ ruby test.rb
Traceback (most recent call last):
        5: from test.rb:4:in `<main>'
        4: from test.rb:4:in `open'
        3: from test.rb:5:in `block in <main>'
        2: from /usr/lib/ruby/2.7.0/erb.rb:905:in `result'
        1: from /usr/lib/ruby/2.7.0/erb.rb:905:in `eval'
(erb):2:in `block in <main>': undefined local variable or method `i' for main:Object (NameError)

Any ideas gratefully received! :)

CodePudding user response:

If you want to use syntax like % some code in ERB you need to pass trim_mode: '%' when you initialize ERB. Like this:

ERB.new(File.read("test.erb"), trim_mode: "%")

Other possible options for initialization are described here.

Or, alternatively, you can keep your ERB initializer as it is and instead change your ERB code to

<% for i in 0..1 %>
  foo<%=i%>;
<% end %>
  • Related