为什么我在以下代码中没有收到任何输出?

时间:2015-03-25 09:41:22

标签: ruby erb

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= @weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

结果是今天是。这不是预期的。怎么解决?

1 个答案:

答案 0 :(得分:1)

因为您没有定义@weekday。您在模板中使用实例变量,因此您需要定义它:

require 'erb'

@weekday = Time.now.strftime('%A')
simple_template = "Today is <%= @weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

OR

您可以在模板中使用已定义的局部变量:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()