I have a loop in HAML as follows:
- first = true
- @years.each do |year|
%th #{year}
- first = false and next if first == true
%th #{year} Δ
%th #{year} Δ %
The goal is to add delta
columns for years following the first year.
Debugging the row I can see that first
is correctly being set to false
, however the columns following the next
are still being outputted.
If I perform the comparison without booleans, things work as expected:
- first = :true
- @years.each do |year|
%th #{year}
- first = :false and next if first == :true
%th #{year} Δ
%th #{year} Δ %
Does anyone understand what's going on under the hood?
Using Ruby 2.2.3
and HAML 4.0.7
Ruby, like many languages, has something called short-circuiting in boolean logic. Expressions like 'and' are only true if both expressions are true, so if the first expression is false, the second is never called.
In your case, (first = false)
resolves to false, so the and
expression returns false without ever running next
.
This is an important feature for expressions like:
do.something if !myobject.nil? and myobject.some_method
Without short-circuiting, myobject.some_method would throw an error every time myobject was nil.
You can avoid the problem by writing your haml this way:
- first = true
- @years.each do |year|
%th #{year}
- if first == true
- first = false
- next
%th #{year} Δ
%th #{year} Δ %