1

我注意到,在 Ruby 中,代码用未定义的ifx = x初始化了一个局部变量。例如,这可以在 ERB 模板中用于检查是否定义了局部变量并具有“true-ish”值:xnilx

<% if header = header %>
  <h1><%= header %></h1>
<% end %>

那么,这是一个功能还是一个错误?它是否记录在某处?

4

2 回答 2

4

这可能有效,但我认为它掩盖了你的意图。

如果您想检查是否定义了某些内容,那么您应该说

if defined?(header) && header

但是在部分中,我通常会在模板开头默认所有值

例如(带火腿)

- # input header is optional
- header ||= nil

- if header
  %h1 This is the header

%p this is the rest of the partial
于 2013-02-24T22:44:07.530 回答
-4

这既不是功能也不是错误。您可以通过调用它来简单地测试局部变量的真实性,就好像它没有初始化一样,默认情况下它会返回 nil。

<% if header %>
  <h1><%= header %></h1>
<% end %>
于 2013-02-24T22:41:47.937 回答