ruby 如何在数组上循环

uttx8gqw  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(78)

我不能简单地用ruby erb模板系统循环数组.
下面是我的模板:

<% ['foo', 'bar'].each do |val| -%>
<%= val %>
<% end -%>

下面是命令行和结果

erb test.erb
/usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `eval': test.erb:1: syntax error, unexpected ';' (SyntaxError)
'foo', 'bar'].each do |val| -; _erbout.concat "\n"
                              ^
test.erb:3: syntax error, unexpected ';'
;  end -; _erbout.concat "\n"
         ^
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `result'
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:878:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:149:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:170:in `<main>'

这个简单的例子有什么问题吗?
免责声明:我是一个Ruby和Erb noob ^^

vxbzzdmp

vxbzzdmp1#

你不应该在“%"前面加上“-”。

<% ['foo', 'bar'].each do |val| %>
    <%= val %>
<% end %>

这个应该能用

3duebb1j

3duebb1j2#

您必须将 * 修剪模式 * 设置为-

$ erb -T - test.erb
foo
bar

从手册页:

**-T** mode   Specifies trim mode (default 0). mode can be one of
          **0**   EOL remains after the embedded ruby script is evaluated.
          **1**   EOL is removed if the line ends with **%>**.
          **2**   EOL is removed if the line starts with **<%** and ends with **%>**.
          **-**   EOL is removed if the line ends with **-%>**. And leading whitespaces
              are removed if the erb directive starts with **<%-**.

相关问题