IRB - NameError: undefined local variable or method for main:Object

IRB - NameError: undefined local variable or method for main:Object

我想了解 ERB 在 IRB 中是如何工作的。

>> require 'erb'
=> true

>> weekday = Time.now.strftime('%A')
=> "Wednesday"

>> simple_template = "Today is <%= weekday %>."
=> "Today is <%= weekday %>."

>> renderer = ERB.new(simple_template)
=> #<ERB:0x287f568 @safe_level=nil, @src="#coding:IBM437\n_erbout = ''; _erbout.concat \"Today is \"; _erbout.concat(( weekday ).to_s); _erbout.concat \".\"; _erbout.force_encoding(__ENCODING__)", @encoding=#<Encoding:IBM437>, @filename=nil, @lineno=0>

>> puts output = renderer.result()
NameError: undefined local variable or method `weekday' for main:Object
        from (erb):1:in `<main>'
        from C:/Ruby22/lib/ruby/2.2.0/erb.rb:863:in `eval'
        from C:/Ruby22/lib/ruby/2.2.0/erb.rb:863:in `result'
        from (irb):5
        from C:/Ruby22/bin/irb:11:in `<main>'

我无法找出上述错误的原因,因为我可以看到变量正在返回它的值。

>> weekday
=> "Wednesday"

现在,当我获取代码并将其放入文件时,运行 没问题。请解释。

1.8.7-p376 :004 > require 'erb'
=> true 

1.8.7-p376 :005 > @weekday = Time.now.strftime('%A')
=> "Wednesday" 

1.8.7-p376 :006 > simple_template = "Today is <%= @weekday %>."
=> "Today is <%= @weekday %>." 

1.8.7-p376 :007 > renderer = ERB.new(simple_template)
=> #<ERB:0x10e46a8e8 @src="_erbout = ''; _erbout.concat \"Today is \"; _erbout.concat(( @weekday ).to_s); _erbout.concat \".\"; _erbout", @filename=nil, @safe_level=nil> 

1.8.7-p376 :009 > puts output = renderer.result()
Today is Wednesday.
=> nil 

您想通过附加 @ 使 weekday 成为一个实例变量。像这样,@weekday = Time.now.strftime('%A')

puts output = renderer.result()

无法访问您的上下文,因此它看不到变量weekday您需要传递当前上下文("binding")

试试看

puts output = renderer.result(binding)

您引用的 this blog post about ERB 似乎不正确。 ERB渲染方法需要接收一个binding,它定义了从哪里获取局部变量:

renderer.result(binding)

值得注意的是,文章使用了很多在 Ruby 中被认为是非标准的做法,例如在方法定义和调用中包含空参数列表。

让它成为实例变量:ERB 查找实例变量:

@weekday = Time.now.strftime('%A')
ERB.new("Today is <%= @weekday %>.").result
#⇒ "Today is Wednesday."