【问题标题】:Ruby Undefined Local VariableRuby 未定义的局部变量
【发布时间】:2011-06-02 15:36:12
【问题描述】:

以下是 ERB 教程中的代码。当我尝试执行代码时,编译器抱怨说“(erb):16: undefined local variable or method `priority' for main:Object (NameError)”。我无法弄清楚原因。有人可以帮帮我吗?

require "erb"

# Create template.
template = %q{
  From:  James Edward Gray II <james@grayproductions.net>
  To:  <%= to %>
  Subject:  Addressing Needs

  <%= to[/\w+/] %>:

  Just wanted to send a quick note assuring that your needs are being
  addressed.

  I want you to know that my team will keep working on the issues,
  especially:

  <%# ignore numerous minor requests -- focus on priorities %>
  % priorities.each do |priority|
    * <%= priority %>
  % end

  Thanks for your patience.

  James Edward Gray II
}.gsub(/^  /, '')

message = ERB.new(template, 0, "%<>")

# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
               "Document Modules",
               "Answer Questions on Ruby Talk" ]

# Produce result.
email = message.result
puts email

【问题讨论】:

    标签: ruby undefined erb local-variables


    【解决方案1】:

    那个 ERB 模板看起来有问题,这是由您的缩进引起的问题。你只需要修复中间:

      <% priorities.each do |priority| %>
        * <%= priority %>
      <% end %>
    

    另一种语法是在行的最开始处有一个%。在您的情况下,您无意中添加了一些导致 ERB 部分无效的空格。

    【讨论】:

    • 顺便问一下 gsub 在这种情况下会做什么?在模板或生成的文本中替换?
    • 它删除字符串中每行开头的前两个空格。这似乎解决了缩进问题,但实际上是一个次优的解决方案。最好使用&lt;&lt;-style HERE 文档。
    猜你喜欢
    • 2012-03-29
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多