Ruby HAML 不尊重布尔值?

Ruby HAML doesn't respect booleans?

我在 HAML 中有一个循环如下:

- first = true
- @years.each do |year|
  %th #{year}
  - first = false and next if first == true
  %th #{year} Δ
  %th #{year} Δ %

目标是为第一年之后的年份添加 delta 列。

调试该行我可以看到 first 被正确设置为 false,但是 next 之后的列仍在输出。

如果我在没有布尔值的情况下执行比较,事情会按预期进行:

- first = :true
- @years.each do |year|
  %th #{year}
  - first = :false and next if first == :true
  %th #{year} Δ
  %th #{year} Δ %

有人知道幕后发生了什么吗?

使用 Ruby 2.2.3HAML 4.0.7

Ruby,像许多语言一样,在布尔逻辑中有一种叫做短路的东西。像 'and' 这样的表达式只有在两个表达式都为真时才为真,所以如果第一个表达式为假,则永远不会调用第二个。

在您的情况下,(first = false) 解析为 false,因此 and 表达式 returns false 永远不会 运行 next.

这是表达式的一个重要特征,例如:

do.something if !myobject.nil? and myobject.some_method

如果没有短路,myobject.some_method 每次 myobject 为 nil 时都会抛出错误。

你可以通过这样写你的 haml 来避免这个问题:

- first = true
- @years.each do |year|
  %th #{year}
  - if first == true
    - first = false
    - next
  %th #{year} Δ
  %th #{year} Δ %