Ruby templates: How to pass variables into inlined ERB?

Viewed 62266

I have an ERB template inlined into Ruby code:

require 'erb'

DATA = {
    :a => "HELLO",
    :b => "WORLD",
}

template = ERB.new <<-EOF
    current key is: <%= current %>
    current value is: <%= DATA[current] %>
EOF

DATA.keys.each do |current|
    result = template.result
    outputFile = File.new(current.to_s,File::CREAT|File::TRUNC|File::RDWR)
    outputFile.write(result)
    outputFile.close
end

I can't pass the variable "current" into the template.

The error is:

(erb):1: undefined local variable or method `current' for main:Object (NameError)

How do I fix this?

10 Answers

Maybe the cleanest solution would be to pass specific current local variable to erb template instead of passing the entire binding. It's possible with ERB#result_with_hash method (introduced in Ruby 2.5)

DATA.keys.each do |current|
  result = template.result_with_hash(current: current)
...
Related