我在Ruby代码中内联了一个ERB模板:

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

我无法将变量"current"传递到模板中.

错误是:

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

我该怎么解决这个问题?

推荐答案

知道了!

我创建了一个绑定类

class BindMe
    def initialize(key,val)
        @key=key
        @val=val
    end
    def get_binding
        return binding()
    end
end

并将一个实例传递给ERB

dataHash.keys.each do |current|
    key = current.to_s
    val = dataHash[key]

    # here, I pass the bindings instance to ERB
    bindMe = BindMe.new(key,val)

    result = template.result(bindMe.get_binding)

    # unnecessary code goes here
end

这个erb模板文件如下所示:

Key: <%= @key %>

Ruby相关问答推荐

Ruby插值法导致无序输出

RSpec 中有没有一种方法可以同时断言调用次数和参数列表?

如何用 yield_self 断链

将 pp 的结果(或输出到控制台的任何内容)放入字符串

在Ruby中将嵌套哈希键从CamelCase转换为snake_case

为什么安全导航比在 Rails 中使用 try 更好?

Ruby 相当于 Groovy 的 Elvis (?:) 运算符?

Windows 上的 Jekyll:Pygments 不工作

在基于值的哈希数组上唯一

RSpec: stubbing Kernel::sleep?

如何在 Ruby 中临时重定向标准错误?

如何从 SystemStackError 中获取回溯:堆栈级别太深?

在 Ruby 中,有没有办法使用 hash.each_with_index do |[k,v], i| 之类的东西?

删除/取消定义类方法

如何在 Ruby 中取消定义类?

向实例对象添加方法

如何判断变量是数字还是字符串?

=== 与 == 在 Ruby 中

将 Nokogiri 文档转换为 Ruby 哈希

如何创建一个 Gemfile?